javascript String.prototype.replace() 删除破折号和下划线
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21357171/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
String.prototype.replace() to remove dashes and underscores
提问by Rodrigo Medeiros
I'm trying to remove all ocurrences of dashes and underscores of a string with String.prototype.replace()
, but it's not working and I don't know why. My code:
我正在尝试使用 删除字符串的所有破折号和下划线String.prototype.replace()
,但它不起作用,我不知道为什么。我的代码:
var str = "dash-and_underscore";
str = str.replace(/_|\-/, " ");
console.log(str);
outputs:
输出:
"dash and_underscore"
in the Chrome console.
在 Chrome 控制台中。
Since the |
acts like the OR
opperator, what am I doing wrong? I've tried the solution here, but it didn't work, or I'm too dumb to understand - which is an option ;)
既然|
行为像OR
经营者,我做错了什么?我在这里尝试了解决方案,但没有用,或者我太笨了无法理解 - 这是一个选项;)
回答by Casimir et Hippolyte
Try this:
试试这个:
str = str.replace(/[_-]/g, " ");
[..]
defines a character classg
means global research
[..]
定义一个字符类g
意味着全球研究
(You can write it with a quantifier /[_-]+/g
to remove several consecutive characters at a time.)
(您可以使用量词编写它以一次/[_-]+/g
删除多个连续字符。)
or
或者
str = str.replace(/_|-/g, " ");
that is correct too, but slower. Note that the dash doesn't need to be escaped out of a character class since it isn't a special character.
这也是正确的,但速度较慢。请注意,破折号不需要从字符类中转义出来,因为它不是特殊字符。