Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript how to make a split() case insensitive

Tags:

javascript

I want to split on Red and red how can I make split case insensitive?

const str = "my Red balloon"
const searchTxt = "red"
const strArr = str.split(searchTxt);

I've tried variations of

const strArr = str.split(/searchTxt/gi);
like image 664
Bill Avatar asked Apr 23 '21 09:04

Bill


People also ask

How do you make a case insensitive in JavaScript?

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.

Is JavaScript replace case-sensitive?

JavaScript String Replace | Case Insensitive. The . replace function in JavaScript helps developers replace all the occurrences of a string in a text. However, many of us developers use this method in the wrong way while writing the code.

Is there a split function in JavaScript?

split() The split() method takes a pattern and divides a String into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array.

What is case insensitive in JavaScript?

Comparing strings in a case insensitive manner means to compare them without taking care of the uppercase and lowercase letters. To perform this operation the most preferred method is to use either toUpperCase() or toLowerCase() function.


3 Answers

Use the RegExp constructor with the desired flags as second argument

RegExp(expression, flags)

Important: when passing arbitrary strings (like from a user input) to the RegExp constructor - make always sure to escape RegExp special characters the RegExp might confuse as regular expression tokens such as . (any character) ? (one or more) etc, etc. See the two link-demos below.

const str = "my Red balloon"
const searchTxt = "red"
const regEscape = v => v.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
const strArr = str.split(new RegExp(regEscape(searchTxt), "ig"));
console.log(strArr)
  • Example with wrong output without escaping
  • Example with correct output with escaping
like image 108
Roko C. Buljan Avatar answered Oct 20 '22 18:10

Roko C. Buljan


In order to use a variable in a regular expression, you need to use the RegExp constructor. No need to use the g flag, since split will always look for all occurrences:

const str = "my Red balloon"
const searchTxt = "red"
const strArr = str.split( new RegExp(searchTxt, 'i') );
console.log(strArr);
like image 35
blex Avatar answered Oct 20 '22 20:10

blex


Simply put all to lower case:

const str = "my Red balloon"
const searchTxt = "red"
const strArr = str.toLowerCase().split(searchTxt.toLowerCase());
like image 1
Ast Avatar answered Oct 20 '22 18:10

Ast