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
  • jQuery is JavaScript! (What you want is to not use it.) – ComFreek Commented Sep 11, 2013 at 12:04
  • and what if it is Howl ? – Ivan Chernykh Commented Sep 11, 2013 at 12:04
  • I don't want to include jquery library – Anand Jha Commented Sep 11, 2013 at 12:05
  • 5 Stop posting indexOf() answers! – ComFreek Commented Sep 11, 2013 at 12:09
  • 1 @duffymo the last guy I heard saying something similar is missing now for 7 years already... :( – pandita Commented Sep 11, 2013 at 12:28
 |  Show 18 more comments

4 Answers 4

Reset to default 23

You 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