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?
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.
/[^az]+/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
/[^az]+/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.
/[^az]+/gi
[space][.] Matches globally case insensitive
s.replace(/[^az]+/gi, "")
Gives the desired string
"Thequickbrownfoxjumpsoverthelazydog"
length = 35
Afterwards you can split it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.