Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search whole word in string

Tags:

javascript

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
   }
like image 328
Anand Jha Avatar asked Sep 11 '13 12:09

Anand Jha


People also ask

How do I search for a word in a string?

To find a word in the string, we are using indexOf() and contains() methods of String class. The indexOf() method is used to find an index of the specified substring in the present string. It returns a positive integer as an index if substring found else returns -1.

How do you match a whole word in Python?

You can use the simple Python membership operator. You can use a default regex with no special metacharacters. You can use the word boundary metacharacter '\b' to match only whole words. You can match case-insensitive by using the flags argument re.

How do I find a word in a string python?

String find() in Python Just call the method on the string object to search for a string, like so: obj. find(“search”). The find() method searches for a query string and returns the character position if found. If the string is not found, it returns -1.

What does find () mean in Python?

Definition and Usage The find() method finds the first occurrence of the specified value. The find() method returns -1 if the value is not found. The find() method is almost the same as the index() method, the only difference is that the index() method raises an exception if the value is not found. ( See example below)


2 Answers

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);
like image 109
ComFreek Avatar answered Oct 01 '22 01:10

ComFreek


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.

like image 21
poida Avatar answered Oct 01 '22 02:10

poida