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 ?
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.
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.
JavaScript String trim() The trim() method removes whitespace from both sides of a string.
Use the str. replace() method to remove the hyphens from a string, e.g. result = my_str.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With