关于JavaScript RegEx - 替换所有标点符号,包括下划线

时间:2014-12-10 08:25:46

标签: javascript regex

在javascript中,如何用连字符替换所有标点符号(包括下划线)标记?而且,它不应该包含多个连字符。

我尝试"h....e l___l^^0".replace(/[^\w]/g, "-"),但它给了我h----e---l___l--0

我该怎么办才能让我回复h-e-l-l-0

3 个答案:

答案 0 :(得分:3)

+重复前一个标记一次或多次。

> "h....e l___l^^0".replace(/[\W_]+/g, "-")
'h-e-l-l-0'

[\W_]+匹配非单词字符或_一次或多次。

答案 1 :(得分:1)

您需要做的就是为regex

添加一个quatifier +
"h....e   l___l^^0".replace(/[^a-zA-Z0-9]+/g, "-")

注意

  • 而不是[^\w][^a-zA-Z0-9]+,因为\w包含_因此,如果您提供[^\w]
  • ,则不会被替换

答案 2 :(得分:1)

Regex101

[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~ ]+

Regular expression visualization

<强>描述

[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~ ]+ match a single character present in the list below
    Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
    !"#$%&'()*+, a single character in the list !"#$%&'()*+, literally (case sensitive)
    \- matches the character - literally
    . the literal character .
    \/ matches the character / literally
    :;<=>?@[ a single character in the list :;<=>?@[ literally (case sensitive)
    \\ matches the character \ literally
    \] matches the character ] literally
    ^_`{|}~  a single character in the list ^_`{|}~  literally
g modifier: global. All matches (don't return on first match)

<强> JS

alert("h....e l___l^^0".replace(/[!"#$%&'()*+,\-.\/ :;<=>?@[\\\]^_`{|}~]+/g, "-"));

<强>结果:

  

H-E-L-L-0