Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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
   }

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
357 views
Welcome To Ask or Share your Answers For Others

1 Answer

You could use regular expressions:

how

Example:

/how/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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...