在javascript中,如何用连字符替换所有标点符号(包括下划线)标记?而且,它不应该包含多个连字符。
我尝试"h....e l___l^^0".replace(/[^\w]/g, "-")
,但它给了我h----e---l___l--0
我该怎么办才能让我回复h-e-l-l-0
?
答案 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)
[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~ ]+
<强>描述强>
[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~ ]+ 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