簡體   English   中英

確定字符串是否具有子字符串(單詞)

[英]Determining whether a string has a substring (word)

我嘗試使用條件查詢來驗證字符串是否包含某個單詞,例如:我想使用一種方法(regex?)來查找字符串是否具有文本"&SWE>clickable"

var text1 = "layer_legs";
var text2 = "layer_head&SWE>clickable";

if (....)
   document.write ("the layer is clickable")
else
   document.write ("the layer is not clickable")

我怎樣才能做到這一點?

您可以使用String.indexOf 如果找不到該字符串,則返回-1,否則返回找到該字符串的索引。 您可以像這樣使用它:

if (s.indexOf("&SWE>clickable") !== -1) { ... }
 if (text2.indexOf("&SWE>clickable") > -1) {
    ....
if (/&SWE>clickable/g.test(text2)) {
    // exists
}

編輯:像其他人一樣使用indexOf可能會更好,因為它更具可讀性,並且您不需要轉義字符。 而且可以說是更快:/

嘗試這個 :

if (text1.indexOf('&SWE>clickable')>=0){ ... }

或正則表達式方式:

var re = new RegExp('\&SWE\>clickable')
if (re.test(text1)){ ... }
 if(text1.indexOf(text2)) 
    document.write ("the layer is clickable") 
 else 
    document.write ("the layer is not clickable")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM