javascript val.replace(/[^a-zA-Z_-0-9]/g, '') 产生语法错误:字符类中的范围无效

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12142829/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 15:25:37  来源:igfitidea点击:

val.replace(/[^a-zA-Z_-0-9]/g, '') produce SyntaxError: invalid range in character class

javascriptregex

提问by Oleksandr IY

I need to replace all chars which are not match with range a-zA-Z_-0-9. So I do val.replace(/[^a-zA-Z_-0-9]/g, '')but get error. How can I bit this? Thanks

我需要替换所有与 range 不匹配的字符a-zA-Z_-0-9。所以我做val.replace(/[^a-zA-Z_-0-9]/g, '')但得到错误。我怎么能咬这个?谢谢

回答by Dmitry

If you want to include the minus sign "-" in the character class, you have to put it into the end of range:

如果要在字符类中包含减号“-”,则必须将其放入范围末尾:

val.replace(/[^a-zA-Z_0-9-]/g, '')

回答by sQVe

I would prefer this regex:

我更喜欢这个正则表达式:

val.replace(/[^\w-]+/gi, "");

回答by pimvdb

You expect that -character to be parsed as being literal, but it is in fact parsed as a range: _-0means _to 0, just like a-zmeans ato z. However, since _has a higher character code than 0, you get an error.

您希望该-字符被解析为文字,但实际上它被解析为一个范围:_-0表示_to 0,就像a-z表示ato 一样z。但是,由于_字符代码高于0,您会收到错误消息。

In your case, just escape it: \-. This is parsed as the -character.

在您的情况下,只需将其转义即可:\-. 这被解析为-字符。

回答by Nicholas Albion

You need to escape the "-"

你需要逃避“-”

val.replace(/[^a-zA-Z_\-0-9]/g, '')

回答by Birei

You have a bad range, remove the -between _and the number range and put it at the end or at the beginning.

你有一个错误的范围,删除-之间_和数字范围并将其放在末尾或开头。

回答by Dariush Jafari

try this:

试试这个:

val.replace(/[^a-zA-Z_0-9-]/g, '');

回答by edgar berumen

$(this).val($(this).val().replace(/[^a-zA-Z_0-9-]/g, ''));