Replacing all non-alphanumeric characters with empty strings

I tried using this but didn't work-

return value.replaceAll("/[^A-Za-z0-9 ]/", "");

Solution 1:

Use [^A-Za-z0-9].

Note: removed the space since that is not typically considered alphanumeric.

Solution 2:

Try

return value.replaceAll("[^A-Za-z0-9]", "");

or

return value.replaceAll("[\\W]|_", "");

Solution 3:

You should be aware that [^a-zA-Z] will replace characters not being itself in the character range A-Z/a-z. That means special characters like é, ß etc. or cyrillic characters and such will be removed.

If the replacement of these characters is not wanted use pre-defined character classes instead:

 str.replaceAll("[^\\p{IsAlphabetic}\\p{IsDigit}]", "");

PS: \p{Alnum} does not achieve this effect, it acts the same as [A-Za-z0-9].

Solution 4:

return value.replaceAll("[^A-Za-z0-9 ]", "");

This will leave spaces intact. I assume that's what you want. Otherwise, remove the space from the regex.