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
}
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.
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.
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.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With