7

I'm trying to remove any non alphanumeric characters ANY white spaces from a string.

Currently I have a two step solution and would like to make it in to one.

var name_parsed = name.replace(/[^0-9a-zA-Z ]/g, ''); // Bacon, Juice | 234
name_parsed = name_parsed.replace(/ /g,'')
console.log(name_parsed); //BaconJuice234

Could someone let me know how to achieve above in one execution and not two?

5
  • 3
    You include a whitespace in the original regular expression! Commented Jun 5, 2014 at 14:03
  • @epascarello oh geez...No wonder I tried and tried! Thank you. Commented Jun 5, 2014 at 14:04
  • Why not just replace(/\W+/g, '') Commented Jun 5, 2014 at 14:06
  • @adeneo Because \w includes _ as well. Commented Jun 5, 2014 at 15:05
  • @VisioN - true, there's the underscore, but as long as the string doesn't contain an underscore it's not an issue. Was just a suggestion really ! Commented Jun 5, 2014 at 15:45

1 Answer 1

28

Remove the space from the first set and will do the job:

name.replace(/[^0-9a-zA-Z]/g, '');

You may read this code as "remove all characters that are not digits ([0-9]) and alpha characters ([a-zA-Z])".

Alternatively, you can use the i flag to make your regular expression ignore case. Then the code can be simplified:

name.replace(/[^0-9a-z]/gi, ''); 
Sign up to request clarification or add additional context in comments.

2 Comments

@VisioN this doesn't work for me in the following example: "sdf234 234dfsf".replace(/[^0-9a-zA-Z]/g, '') I just did this in Firebug console, not sure why it wouldn't work. Result = "sdf234234dfsf"
@Jacques What exactly doesn't work? To your result it works as expected: it removed all characters apart from digits and Latin letters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.