![](/img/trans.png)
[英]RegExp - How to check if a string contains a substring in the certain position?
[英]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.