繁体   English   中英

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

[英]Check a certain section of string if it contains a substring

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

到目前为止,这是我的代码:

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

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

因此,当前它检查ColourInput是否包含字符串中从位置0 # ,但是我想对其进行限制,因此它仅检查ColourInput的第一个字符

我该怎么做呢? 任何帮助表示赞赏

备用,使用startsWith()

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

使用此获取第一个元素:

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

如果我正确理解,它将只检查值的第一个字符(如果它是“#”),这就是您要查找的内容。

尝试regexp

/^#/.test(sHexValue)

要获得完整的十六进制颜色,请使用此

/^#[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

使用此代码检查字符串中char的索引是否为0。

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

注意: IE浏览器可能不支持include()方法。 因此,只需检查此方法,然后告诉我您是否要面对。 谢谢。

暂无
暂无

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

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