用正则表达式替换Javascript字符串以去除非法字符 [英] Javascript string replace with regex to strip off illegal characters
问题描述
需要一个功能来解除javascript中的一组非法字符: |& ;; $%@<>()+,
Need a function to strip off a set of illegal character in javascript: |&;$%@"<>()+,
这是一个需要用正则表达式解决的经典问题,这意味着现在我有2个问题。
This is a classic problem to be solved with regexes, which means now I have 2 problems.
这就是我所拥有的远:
var cleanString = dirtyString.replace(/\|&;\$%@"<>\(\)\+,/g, "");
我正在使用反斜杠逃避正则表达式特殊字符,但我很难理解什么是继续
I am escaping the regex special chars with a backslash but I am having a hard time trying to understand what's going on.
如果我单独尝试使用单个文字它们中的大多数似乎可以工作,但是一旦我将它们放在同一个正则表达式中,取决于命令替换被打破。
If I try with single literals in isolation most of them seem to work, but once I put them together in the same regex depending on the order the replace is broken.
ie这不起作用 - > dirtyString.replace(/ \ |<> / g,):
i.e. this won't work --> dirtyString.replace(/\|<>/g, ""):
帮助赞赏!
推荐答案
您需要的是字符类。在那,你只需要担心]
, \
和 -
字符(以及 ^
如果你在字符类开头后直接放置它 [
)。
What you need are character classes. In that, you've only to worry about the ]
, \
and -
characters (and ^
if you're placing it straight after the beginning of the character class "[
" ).
语法: [
字符 ]
其中个字符是一个包含字符的列表。
Syntax: [
characters]
where characters is a list with characters.
示例:
var cleanString = dirtyString.replace(/[|&;$%@"<>()+,]/g, "");
这篇关于用正则表达式替换Javascript字符串以去除非法字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!