Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript string remove white spaces and hyphens

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 ?

like image 363
Alon Avatar asked Jul 21 '14 07:07

Alon


People also ask

How do you remove hyphens from a string?

Use the String. replace() method to remove all hyphens from a string, e.g. const hyphensRemoved = str. replace(/-/g, ''); . The replace() method will remove all hyphens from the string by replacing them with empty strings.

How do you replace spaces with dashes?

Use the replace() method to replace spaces with dashes in a string, e.g. str. replace(/\s+/g, '-') . The replace method will return a new string, where each space is replaced by a dash.

How do I remove spaces between words in JavaScript?

JavaScript String trim() The trim() method removes whitespace from both sides of a string.

How do I remove a hyphen from a string in Python?

Use the str. replace() method to remove the hyphens from a string, e.g. result = my_str.


1 Answers

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'
like image 136
Michael Homer Avatar answered Oct 06 '22 23:10

Michael Homer