Javascript string remove spaces and hyphens

I would like to remove spaces and hyphens from the given string.

var string = "john-doe alejnadro"; var new_string = string.replace(/-\s/g,"") 

Doesn't work, but this next line works for me:

 var new_string = string.replace(/-/g,"").replace(/ /g, "") 

How do I do this at a time?

+7
javascript regex
source share
3 answers

Use alternation :

 var new_string = string.replace(/-|\s/g,""); 

a|b will match either a or b , so this matches both hyphens and spaces.

Example:

 > "hyphen-containing string".replace(/-|\s/g,"") 'hyphencontainingstring' 
+17
source share

You should use:

  var new_string = string.replace(/[-\s]/g,"") 

/-\s/ means a hyphen followed by a space.

+5
source share

Use this for hyphen

 var str="185-51-671"; var newStr = str.replace(/-/g, ""); 

White space

 var Actuly = newStr.trim(); 
+4
source share

All Articles