简体   繁体   English

检查字符串的某个部分是否包含子字符串

[英]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 因此,当前它检查ColourInput是否包含字符串中从位置0 # ,但是我想对其进行限制,因此它仅检查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 尝试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. 使用此代码检查字符串中char的索引是否为0。

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

Note : includes() method may not be supported in IE browser. 注意: IE浏览器可能不支持include()方法。 so just check with this method and let me know if you face after this. 因此,只需检查此方法,然后告诉我您是否要面对。 Thanks. 谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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