Remove all special characters with RegExp

I would like a RegExp that will remove all special characters from a string. I am trying something like this but it doesn't work in IE7, though it works in Firefox.

var specialChars = "!@#$^&%*()+=-[]/{}|:<>?,.";

for (var i = 0; i < specialChars.length; i++) {
  stringToReplace = stringToReplace.replace(new RegExp("" + specialChars[i], "gi"), "");
}

A detailed description of the RegExp would be helpful as well.


var desired = stringToReplace.replace(/[^ws]/gi, '')

As was mentioned in the comments it's easier to do this as a whitelist - replace the characters which aren't in your safelist.

The caret ( ^ ) character is the negation of the set [...] , gi say global and case-insensitive (the latter is a bit redundant but I wanted to mention it) and the safelist in this example is digits, word characters, underscores ( w ) and whitespace ( s ).


Note that if you still want to exclude a set, including things like slashes and special characters you can do the following:

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

take special note that in order to also include the "minus" character, you need to escape it with a backslash like the latter group. if you don't it will also select 0-9 which is probably undesired.


Plain Javascript regex does not handle Unicode letters . Do not use [^ws] , this will remove letters with accents (like àèéìòù), not to mention to Cyrillic or Chinese, letters coming from such languages will be completed removed.

You really don't want remove these letters together with all the special characters. You have two chances:

  • Add in your regex all the special characters you don't want remove,
    for example: [^èéòàùìws] .
  • Have a look at xregexp.com. XRegExp adds base support for Unicode matching via the p{...} syntax.
  • var str = "Їжак::: résd,$%& adùf"
    var search = XRegExp('([^?<first>pL ]+)');
    var res = XRegExp.replace(str, search, '',"all");
    
    console.log(res); // returns "Їжак::: resd,adf"
    console.log(str.replace(/[^ws]/gi, '') ); // returns " rsd adf"
    console.log(str.replace(/[^wèéòàùìs]/gi, '') ); // returns " résd adùf"
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xregexp/3.1.1/xregexp-all.js"></script>
    链接地址: http://www.djcxy.com/p/95202.html

    上一篇: 如何在PostgreSQL中设置自动增量主键?

    下一篇: 使用RegExp删除所有特殊字符