Tuesday, December 18, 2018

Javascript how to remove unwanted characters



var desired = stringToReplace.replace(/[^\w\s]/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).

references:
https://stackoverflow.com/questions/4374822/remove-all-special-characters-with-regexp

No comments:

Post a Comment