Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.prototype.replace() to remove dashes and underscores

I'm trying to remove all ocurrences of dashes and underscores of a string with String.prototype.replace(), but it's not working and I don't know why. My code:

var str = "dash-and_underscore";
str = str.replace(/_|\-/, " ");
console.log(str);

outputs:

"dash and_underscore"

in the Chrome console.

Since the | acts like the OR opperator, what am I doing wrong? I've tried the solution here, but it didn't work, or I'm too dumb to understand - which is an option ;)

like image 935
Rodrigo Medeiros Avatar asked Jan 25 '14 22:01

Rodrigo Medeiros


1 Answers

Try this:

str = str.replace(/[_-]/g, " "); 

[..] defines a character class
g means global research

(You can write it with a quantifier /[_-]+/g to remove several consecutive characters at a time.)

or

str = str.replace(/_|-/g, " ");

that is correct too, but slower. Note that the dash doesn't need to be escaped out of a character class since it isn't a special character.

like image 98
Casimir et Hippolyte Avatar answered Oct 27 '22 01:10

Casimir et Hippolyte