Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case insensitive regex in JavaScript

People also ask

Is JavaScript regex case-sensitive?

Regular expression, or simply RegEx JavaScript allows you to write specific search patterns. You can also make the search case-sensitive or insensitive, search for a single JavaScript RegEx match or multiple, look for characters at the beginning or the end of a word.

How do you make a case insensitive in JavaScript?

The best way to do a case insensitive comparison in JavaScript is to use RegExp match() method with the i flag.

Are regex expressions case-sensitive?

By default, the comparison of an input string with any literal characters in a regular expression pattern is case-sensitive, white space in a regular expression pattern is interpreted as literal white-space characters, and capturing groups in a regular expression are named implicitly as well as explicitly.


You can add 'i' modifier that means "ignore case"

var results = new RegExp('[\\?&]' + name + '=([^&#]*)', 'i').exec(window.location.href);

modifiers are given as the second parameter:

new RegExp('[\\?&]' + name + '=([^&#]*)', "i")

Simple one liner. In the example below it replaces every vowel with an X.

function replaceWithRegex(str, regex, replaceWith) {
  return str.replace(regex, replaceWith);
}

replaceWithRegex('HEllo there', /[aeiou]/gi, 'X'); //"HXllX thXrX"

Just an alternative suggestion: when you find yourself reaching for "case insensitive regex", you can usually accomplish the same by just manipulating the case of the strings you are comparing:

const foo = 'HellO, WoRlD!';
const isFoo = 'hello, world!';
return foo.toLowerCase() === isFoo.toLowerCase();

I would also call this easier to read and grok the author's intent!