[英]How to match only the exact word using indexOf or includes in JavaScript
我想使用javascript只搜索字符串中的特定單詞。 但是使用match,indexOf或includes不能正常工作。 假設
let str = "Widget test";
if (~str.indexOf("Widge")) {
console.log( 'Found it!' );
}
它會打印發現它,因為它不匹配整個單詞只有子串。 如果只有匹配是Widget,我怎么能將它返回到找到
但我想要的是:
如果輸入string = Widget,則輸出= true
如果輸入string = Widge,則輸出= false
要匹配確切的單詞,您必須使用正則表達式。
/\\bWidget\\b/
將匹配整個單詞。
在你的例子中:
let str = "Widget";
if (str.search(/\bWidget\b/) >= 0) {
console.log( 'Found it!' );
}
你也可以嘗試一下。
let str = "Widget test";
if(str.split(" ").indexOf('Widge') > -1) {
console.log( 'Found it!' );
}
在嘗試回答這個問題時,提供了正確的答案。 還有點不清楚OP究竟想要什么......
...所以在同一時間我寫了這個糟糕的〜黑客〜解決方案:
const matchType = (source = '', target = '') => { const match = source.match(target) || []; return (!isNaN(match.index) && !!~match.index) ? match.input === target ? 'complete' : 'partial' : 'none'; }; console.log(matchType('foo', 'bar')); console.log(matchType('foo', 'fo')); console.log(matchType('foo', 'foo'));
現在你可以有三種不同類型的比賽,不是很酷嗎? :d
如果找不到string而不是indexOf將返回-1,那么你可以檢查索引不等於-1而不是找到的字符串
function match(){ var test = "Widget test"; if (test.indexOf("widget")!= -1) { alert( 'Found it!' ); }else{ alert( 'Sorry,not Found it!' ); } }
<!DOCTYPE html> <html> <body> <button type="button" onclick="match()">Click Me!</button> </body> </html>
let str = "Widget test";
if (str.indexOf("wi")!= -1) {
console.log( 'Found it!' );
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.