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 th
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)
//Syntax
var patt=new RegExp(pattern,modifiers);
//or more simply:
var patt=/pattern/modifiers;
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.
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.
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:
let string = 'PowerRangers'
let regex = /powerrangers/i
let result = regex.test(string) // true
Using the JS 'RegExp' constructor:
let string = 'PowerRangers'
let regex = new RegExp('powerrangers', 'i')
let result = regex.test(string)
Pass the i
modifier as second argument:
new RegExp('^' + query, 'i');
Have a look at the documentation for more information.