在字符串中搜索整个单词 [英] Search whole word in string
本文介绍了在字符串中搜索整个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找用javascript(而不是jquery)编写的函数,如果给定的单词完全匹配(不应区分大小写),该函数将返回true.
I am looking for a function written in javascript ( not in jquery) which will return true if the given word exactly matches ( should not be case sensitive).
喜欢..
var searchOnstring=" Hi, how are doing?"
if( searchText=='ho'){
//output : false
}
if( searchText=='How'){
//output : true
}
谢谢.
推荐答案
您可以使用正则表达式:
You could use regular expressions:
\bhow\b
示例:
/\bhow\b/i.test(searchOnstring);
如果要使用可变单词(例如,通过用户输入),则必须注意不要包含特殊的RegExp字符.
If you want to have a variable word (e.g. from a user input), you have to pay attention to not include special RegExp characters.
例如,您必须使用中提供的功能来对它们进行转义.MDN (向下滚动):
function escapeRegExp(string){
return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
var regex = '\\b';
regex += escapeRegExp(yourDynamicString);
regex += '\\b';
new RegExp(regex, "i").test(searchOnstring);
这篇关于在字符串中搜索整个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文