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

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
User0123456789
  • 760
  • 2
  • 10
  • 25
  • 1
    so you want to check if the first character in `sHexValue` is a `#`? You can do: `sHexValue[0] === "#"` if that's the case – Nick Parsons Mar 14 '19 at 11:03
  • 1
    You can check the characters in a string in a similar manner to an array. I.e, `sHexValue[0] === '#'`? – Lewis Mar 14 '19 at 11:03
  • 3
    Possible duplicate of [How to get first character of string?](https://stackoverflow.com/questions/3427132/how-to-get-first-character-of-string) and [Check First Char In String](https://stackoverflow.com/questions/6348325) and [How to get first letter from string using jquery](https://stackoverflow.com/questions/18887742) – adiga Mar 14 '19 at 11:03
  • you only want to check the first character though? – messerbill Mar 14 '19 at 11:05

5 Answers5

2

Alternate, using startsWith()

document.getElementById("ColourInput").value.startsWith('#')
User863
  • 19,346
  • 2
  • 17
  • 41
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.

Stanimirovv
  • 3,064
  • 8
  • 32
  • 56
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()">
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
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
Rahul Raut
  • 623
  • 6
  • 21
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.

Harsh_Jani
  • 27
  • 1