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
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
Share Improve this question asked May 11, 2015 at 23:20 Alex DaroAlex Daro 4291 gold badge8 silver badges18 bronze badges 1- I believe part of your problem is you're not setting the value of 'term' back to itself as part of the operation: term = term.toLowerCase()... – Steve Hynding Commented May 11, 2015 at 23:26
3 Answers
Reset to default 4Or 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, ''));
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, '');
Or something like this :
var term = "jeni's splendid ice cream";
term.replace(new RegExp('[^a-z\']', 'g'), '');
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745330324a4622848.html
评论列表(0条)