47

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)) {}
Rajat Gupta
  • 25,853
  • 63
  • 179
  • 294
  • Does this answer your question? [Case insensitive regex in JavaScript](https://stackoverflow.com/questions/3939715/case-insensitive-regex-in-javascript) – shreyasm-dev Feb 17 '21 at 19:49

6 Answers6

84

Pass the i modifier as second argument:

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

Have a look at the documentation for more information.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
23

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.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • 3
    @user01: Yes, I tested this in the three browsers that I have installed, and it's faster in all of them: http://jsperf.com/regex-vs-compare – Guffa Feb 20 '13 at 11:36
  • 1
    +1 & thanks. I would going with this solution but as for the question asked about the regex, I should accept the answer acc to that. – Rajat Gupta Feb 20 '13 at 11:45
  • Let's be fair here, ``RegExp('^' + query, 'i')`` is a lot simpler to read for those who know how the JS regex system works. – William Jan 21 '16 at 20:46
  • 2
    @William: However, that fails if the string contains anything that needs to be escaped. The working version is the less readable `RegExp('^' + query.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"), 'i')`. – Guffa Jan 22 '16 at 11:57
  • Fair enough. On Node, I'd assume everything would have already been escaped by the time we reach that point in the code. – William Jan 26 '16 at 18:01
19

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

Kirko
  • 64
  • 4
grepit
  • 21,260
  • 6
  • 105
  • 81
2

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;
SERPRO
  • 10,015
  • 8
  • 46
  • 63
0

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)
Nikhil K Mannem
  • 41
  • 1
  • 1
  • 14
0

2022, ECMA 11

Just created this helper function, I find it more useful and clean than modifying the regex and recreating one everytime.

/**
 * @param {string} str 
 * @param {RegExp} search 
 * @returns {boolean}
 */
function regexStartsWith (str, search, {caseSensitive = true} = {})
{
    var source = search.source
    if (!source.startsWith('^')) source = '^' + source
    var flags = search.flags
    if (!caseSensitive && !flags.includes('i')) flags += 'i'
    var reg = new RegExp(source, flags)
    return reg.test(str)
}

Use it this way:

regexStartsWith('can you Fi    nD me?', /fi.*nd/, {caseSensitive: false})
Alexandre Daubricourt
  • 3,323
  • 1
  • 34
  • 33