简体   繁体   中英

Check a certain section of string if it contains a substring

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

备用,使用startsWith()

document.getElementById("ColourInput").value.startsWith('#')

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.

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()"> 

或者,检查'#'char的索引为0。那么,当我们检查第0个索引时,如果有多个#字符,这将起作用。

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM