Deegii Altangerel
Deegii Altangerel

Reputation: 43

RegEx: Using /i vs. /g (/g replaces whitespace but /i doesn't)

I want an array containing only letters (I'm writing a function to check for pangrams). Using this code with /g gives me an array of only letters and no spaces (lettersArr.length = 34):

var s = "The quick brown fox jumps over the lazy dog."
var lettersArr = s.replace(/[^a-z]+/i, "").split("");
console.log(lettersArr);

However, using the same code with /i gives me an array containing the letters as well the space between quick and brown (lettersArr.length = 43). Since /i is just case-insensitive, shouldn't they give the same results? Is this just a RegEx or Javascript bug?

Upvotes: 4

Views: 147

Answers (2)

varun sharma
varun sharma

Reputation: 1057

/[^a-z]+/i Matches [space][.] First Match which is [space]

When you do

   s.replace(/[^a-z]+/i, "")

gives 'Thequick brown fox jumps over the lazy dog.' length = 43


/[^a-z]+/g [T][space][.] Matches Globally

Capital T is missing here

gives "hequickbrownfoxjumpsoverthelazydog" length = 34


So you need to use both flags because you want to match capital T too.

/[^a-z]+/gi [space][.] Matches globally case insensitive

s.replace(/[^a-z]+/gi, "")

Gives the desired string

"Thequickbrownfoxjumpsoverthelazydog" length = 35

Afterwards you can split it.

Upvotes: 1

wilsonzlin
wilsonzlin

Reputation: 2230

You didn't add the g flag to the regex, so it's only replacing the first match, in your case the first space character.

If you add the g flag, it works:

var s = "The quick brown fox jumps over the lazy dog."
var lettersArr = s.replace(/[^a-z]+/gi, "").split("");
console.log(lettersArr);

Using the g flag means that .replace won't stop at the first match.

Note that without i the array should be of length 35, and with i 34, so I'm not sure how you're getting 26 or 28.

Upvotes: 1

Related Questions