Reputation: 429
I have look around the interwebs but I have yet to find a solid answer. This seems pretty straight forward. Let say I want to replace all characters in a string that is NOT a-z and NOT and apostrophe. For example:
with the string "jeni's splendid ice cream" i would like to replace all characters that are NOT a-z OR an apostrophe. What i have tried so far is:
var term = "jeni's splendid ice cream"
term.toLowerCase().replace(/[^a-z]|[^\']/g, '');
But that didn't seem to work.... Does that look correct to everyone? Just need to sanity check, lol
Upvotes: 3
Views: 3245
Reputation: 12017
The problem is that you are looking for basically anything. Your regex is roughly equal to:
if (character !== 'value1' || character !== 'value2')
Therefore, anything works. You need to instead include the apostrophe in the regex bracket group:
/[^a-z']/g
Also, as Steve Hynding points out, you never actually change the value of term
. To make the code work as you expect, it should be rewritten as:
var term = "jeni's splendid ice cream"
term = term.toLowerCase().replace(/[^a-z']/g, '');
Upvotes: 2
Reputation: 1230
Or something like this :
var term = "jeni's splendid ice cream";
term.replace(new RegExp('[^a-z\']', 'g'), '');
Upvotes: 0
Reputation: 60527
Or statements (|
) belong inside the group, but in the case it is unnecessary. This regex should do the trick:
/[^a-z']/g
var term = "jeni's splendid ice cream"
alert(term.toLowerCase().replace(/[^a-z']/g, ''));
Upvotes: 4