I need to check whether a word starts with a particular substring ignoring the case differences. I have been doing this check using the following regex search pattern but that does not help when there is difference in case across the strings.
my case sensitive way:
var searchPattern = new RegExp('^' + query); if (searchPattern.test(stringToCheck)) {}
The most basic way to do case insensitive string comparison in JavaScript is using either the toLowerCase() or toUpperCase() method to make sure both strings are either all lowercase or all uppercase.
In Java, by default, the regular expression (regex) matching is case sensitive.
Use the test() method to check if a regular expression matches an entire string, e.g. /^hello$/. test(str) . The caret ^ and dollar sign $ match the beginning and end of the string. The test method returns true if the regex matches the entire string, and false otherwise.
Pass the i
modifier as second argument:
new RegExp('^' + query, 'i');
Have a look at the documentation for more information.
You don't need a regular expression at all, just compare the strings:
if (stringToCheck.substr(0, query.length).toUpperCase() == query.toUpperCase())
Demo: http://jsfiddle.net/Guffa/AMD7V/
This also handles cases where you would need to escape characters to make the RegExp solution work, for example if query="4*5?"
which would always match everything otherwise.
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