admin管理员组文章数量:1422029
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'), '');
本文标签: regexJavascript replace all characters that are not az OR apostropheStack Overflow
版权声明:本文标题:regex - Javascript replace all characters that are not a-z OR apostrophe - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745330323a2653782.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论