How to remove everything but:
letters, numbers, spaces, exclamation marks, question marks from a string?
It's important that the method supports international languages (UTF-8).
How to remove everything but:
letters, numbers, spaces, exclamation marks, question marks from a string?
It's important that the method supports international languages (UTF-8).
You can use regex
This will replace everything but a word character, space, exclamation mark, or question.
If you don't want the underscore, you can use just
[A-Za-z0-9]
.For unicode characters, you can add something like
\u0000-\u0080
to the expression. That will exclude all characters within that unicode range. You'll have to specify the range for the characters you don't want removed. You can see all the codes on Unicode Map. Just add in the characters you want kept or a range of characters.For example:
This will allow all the previously mentioned characters, the range from
\u0000-\u0080
and\u0082
. It will remove\u0081
.Both answers posted so far left out the question mark. I would comment on them, but don't have enough rep yet.
David is correct, sachleen's regex will leave underscores behind. rcdmk's regex, modified as follows, will do the trick, although if you care about international characters things might get a lot more complicated.
This will leave behind new lines and tabs as well as spaces. If you want to get rid of new lines and tabs as well, change it to:
Should return
ABCabc123
You can try with a regular expression like:
var cleaned = someString.replace(/[^a-zA-Z0-9! ]+/g, "");