0

I want to check a certain section of my string if it contains a substring.

This is my code so far:

var sHexValue = document.getElementById("ColourInput").value;
fnDebugMessage(sHexValue);

if (sHexValue.includes("#", 0)) {
  fnDebugMessage("TRUE");
}

So currently it checks the ColourInput if it contains # from the position 0 in the string, however I want to restrict it so it checks only the first character of ColourInput

How do I do this? Any help is appreciated

4
  • 1
    so you want to check if the first character in sHexValue is a #? You can do: sHexValue[0] === "#" if that's the case Commented Mar 14, 2019 at 11:03
  • 1
    You can check the characters in a string in a similar manner to an array. I.e, sHexValue[0] === '#'? Commented Mar 14, 2019 at 11:03
  • 3
    Possible duplicate of How to get first character of string? and Check First Char In String and How to get first letter from string using jquery Commented Mar 14, 2019 at 11:03
  • you only want to check the first character though? Commented Mar 14, 2019 at 11:05

5 Answers 5

2

Alternate, using startsWith()

document.getElementById("ColourInput").value.startsWith('#')
Sign up to request clarification or add additional context in comments.

1 Comment

Oh ok, I didn't know there is actually a command to check if a string starts with a character
1

Use this to get first element:

 document.getElementById("ColourInput").value.charAt(0) === "#"

This will check only the first character of the value if it is '#' which is what you are looking for, if I understand correctly.

Comments

1

Use this code to check if the index of char in string is 0.

sHexValue.indexOf("#") === 0

Note : includes() method may not be supported in IE browser. so just check with this method and let me know if you face after this. Thanks.

Comments

1

Try regexp

/^#/.test(sHexValue)

for full hex color use this

/^#[A-Fa-f0-9]{6}$/

function check() {
  let sHexValue = document.getElementById("ColourInput").value;
  let msg="Not contains: #";

  if(/^#/.test(sHexValue)) msg="contains: #";

  console.log(msg);

  if(/^#[A-Fa-f0-9]{6}$/.test(sHexValue)) console.log("Color :)");
}
<input id="ColourInput" onkeyup="check()">

1 Comment

Well this it will return true in position of #.
1

Alternate way, check index of '#' char is 0. Well this will work in case of multiple # characters as we are checking for 0th index.

 document.getElementById("ColourInput").value.indexOf('#') === 0

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.