Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to check whether string starts with, ignoring case differences

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)) {} 
like image 786
Rajat Gupta Avatar asked Feb 20 '13 11:02

Rajat Gupta


People also ask

How do you perform a case insensitive comparison of two strings?

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.

Are regex matches case sensitive?

In Java, by default, the regular expression (regex) matching is case sensitive.

How do I check a string in regex?

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.


Video Answer


2 Answers

Pass the i modifier as second argument:

new RegExp('^' + query, 'i'); 

Have a look at the documentation for more information.

like image 173
Felix Kling Avatar answered Sep 18 '22 13:09

Felix Kling


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.

like image 36
Guffa Avatar answered Sep 18 '22 13:09

Guffa