admin管理员组文章数量:1195955
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).
Like...
var searchOnstring = " Hi, how are doing?"
if( searchText == 'ho'){
// Output: false
}
if( searchText == 'How'){
// Output: 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).
Like...
var searchOnstring = " Hi, how are doing?"
if( searchText == 'ho'){
// Output: false
}
if( searchText == 'How'){
// Output: true
}
Share
Improve this question
edited Feb 8, 2022 at 13:42
Peter Mortensen
31.6k22 gold badges109 silver badges133 bronze badges
asked Sep 11, 2013 at 12:03
Anand JhaAnand Jha
10.7k6 gold badges27 silver badges28 bronze badges
23
|
Show 18 more comments
4 Answers
Reset to default 23You could use regular expressions:
\bhow\b
Example:
/\bhow\b/i.test(searchOnstring);
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.
You have to escape them, for example with the function provided in the MDN (scroll down a bit):
function escapeRegExp(string){
return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
var regex = '\\b';
regex += escapeRegExp(yourDynamicString);
regex += '\\b';
new RegExp(regex, "i").test(searchOnstring);
Here is a function that returns true with searchText is contained within searchOnString, ignoring case:
function isMatch(searchOnString, searchText) {
searchText = searchText.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
return searchOnString.match(new RegExp("\\b"+searchText+"\\b", "i")) != null;
}
Update, as mentioned you should escape the input, I'm using the escape function from https://stackoverflow.com/a/3561711/241294.
Something like this will work:
if(/\show\s/i.test(searchOnstring)){
alert("Found how");
}
More on the test() method
Try this:
var s = 'string to check', ss= 'to';
if(s.indexOf(ss) != -1){
//output : true
}
本文标签: javascriptSearch for a whole word in a stringStack Overflow
版权声明:本文标题:javascript - Search for a whole word in a string - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738525124a2092513.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
Howl
? – Ivan Chernykh Commented Sep 11, 2013 at 12:04