Skip to content Skip to sidebar Skip to footer

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

Solution 1:

Pass the i modifier as second argument:

newRegExp('^' + query, 'i');

Have a look at the documentation for more information.

Solution 2:

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.

Solution 3:

I think all the previous answers are correct. Here is another example similar to SERPRO's, but the difference is that there is no new constructor:

Notice:i ignores the case and ^ means "starts with".

var whateverString = "My test String";
 var pattern = /^my/i;
 var result = pattern.test(whateverString);
 if (result === true) {
     console.log(pattern, "pattern matched!");
 } else {
     console.log(pattern, "pattern did NOT match!");
 }

Here is the jsfiddle (old version) if you would like to give it a try.

enter image description here

Solution 4:

In this page you can see that modifiers can be added as second parameter. In your case you're are looking for 'i' (Canse insensitive)

//Syntaxvar patt=newRegExp(pattern,modifiers);

//or more simply:var patt=/pattern/modifiers;

Solution 5:

For cases like these, JS Regex offers a feature called 'flag'. They offer an extra hand in making up Regular Expressions more efficient and widely applicable.

Here, the flag that could be used is the 'i' flag, which ignores cases (upper and lower), and matches irrespective of them (cases).

Literal Notation:

letstring = 'PowerRangers'let regex = /powerrangers/ilet result = regex.test(string) // true

Using the JS 'RegExp' constructor:

letstring = 'PowerRangers'let regex = newRegExp('powerrangers', 'i')
let result = regex.test(string)

Post a Comment for "Regex To Check Whether String Starts With, Ignoring Case Differences"