18

I would like to remove white spaces and hyphens from a 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 it in one go ?

3 Answers 3

47

Use alternation:

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

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

Example:

> "hyphen-containing string".replace(/-|\s/g,"")
'hyphencontainingstring'
Sign up to request clarification or add additional context in comments.

Comments

6

You have to use:

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

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

Comments

4

Use This for Hyphens

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

White Space

var Actuly = newStr.trim();

1 Comment

.trim() will only remove whitespace at the beginning or end of a string

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.