Alex Daro
Alex Daro

Reputation: 429

Javascript replace all characters that are not a-z OR apostrophe

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

Answers (3)

Anonymous
Anonymous

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

issathink
issathink

Reputation: 1230

Or something like this :

var term = "jeni's splendid ice cream";
term.replace(new RegExp('[^a-z\']', 'g'), '');

Upvotes: 0

Alexander O'Mara
Alexander O'Mara

Reputation: 60527

Or statements (|) belong inside the group, but in the case it is unnecessary. This regex should do the trick:

/[^a-z']/g

Working Example:

var term = "jeni's splendid ice cream"
alert(term.toLowerCase().replace(/[^a-z']/g, ''));

Upvotes: 4

Related Questions