Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/465.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
关于JavaScript正则表达式-替换所有标点符号,包括下划线_Javascript_Regex - Fatal编程技术网

关于JavaScript正则表达式-替换所有标点符号,包括下划线

关于JavaScript正则表达式-替换所有标点符号,包括下划线,javascript,regex,Javascript,Regex,在javascript中,如何用连字符替换所有标点符号(包括下划线)?此外,它不应按顺序包含多个连字符 我尝试了“h..e l_uuul^^0”。替换(/[^\w]/g,“-”),但它给了我h---e---l_uul--0 我应该怎么做才能让它返回我h-e-l-l-0?+将上一个令牌重复一次或多次 > "h....e l___l^^0".replace(/[\W_]+/g, "-") 'h-e-l-l-0' [\W\u]+匹配非单词字符或一次或多次。您需要做的就是向regex添加一个四元

在javascript中,如何用连字符替换所有标点符号(包括下划线)?此外,它不应按顺序包含多个连字符

我尝试了
“h..e l_uuul^^0”。替换(/[^\w]/g,“-”)
,但它给了我
h---e---l_uul--0


我应该怎么做才能让它返回我
h-e-l-l-0

+
将上一个令牌重复一次或多次

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

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

您需要做的就是向regex添加一个四元数
+

> "h....e l___l^^0".replace(/[\W_]+/g, "-")
'h-e-l-l-0'
"h....e   l___l^^0".replace(/[^a-zA-Z0-9]+/g, "-")
注意

  • 而不是
    [^\w]
    给出
    [^a-zA-Z0-9]+
    ,因为
    \w
    包含
    \u
    ,因此如果给出
    [^\w]
[!“\\$%&'()*+,\-.\/:;?@[\\\]^{124;}]+

说明

[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~ ]+ 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)
[!“\\$%&'()*+,\-.\/:;?@[\\]^ `{124;}~]+匹配下表中的单个字符
量词:+在一次和无限次之间,尽可能多的次数,根据需要回馈[贪婪]
!“#$%&'()*+,列表中的单个字符!”#$%&'()*+,字面意思(区分大小写)
\-按字面意思匹配字符
. 文字字符。
\/与字符/字面匹配
:;?@[列表中的单个字符:;?@[字面意思(区分大小写)
\\匹配字符\按字面意思匹配
\]按字面意思匹配字符]
^_`{|}~列表中的单个字符^ `{|}~字面意思
g修饰语:全局。所有比赛(第一场比赛不返回)
JS

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

h-e-l-l-0


谢谢你的帮助,投了赞成票;但是@Avinash Raj的解决方案似乎是最简单的!@RuchirGupta没问题,希望它将来能帮助你。我使用了
[\W\u]
,它按照@Avinash Raj的建议工作,无论如何谢谢你的帮助!