Reputation: 1800
I have a variable that looks like this:
var name = 'John, Doe';
this name could be represented like this too:
var name = 'john , doe';
or
var name = 'john ,doe';
or even
var name = 'john , doe';
In all occurances, I'd like to make the name end up like this:
var name = 'john*doe';
I've violated the DRY principles already, by doing something like this:
name= name.replace(' ,', '*');
name= name.replace(', ', '*');
name = name.replace(',', '*');
and this doesn't even taken into account extra white space. Is there a regex pattern I can apply to take care of this?
Thanks
Upvotes: 0
Views: 5037
Reputation: 26134
Try this following?
name = name.replace(/\s*,\s*/, '*');
@Bergi's answer also adds the g
flag to catch all commas (with whitespace), so depending on your input, that may work as well.
Upvotes: 4
Reputation: 8420
You can do the following
name = name.replace(/[ ]*,[ ]*/, '*');
I've put space in [] for clarity.
Please note that regex in JavaScript need /
around it. The pattern matches 0 or 1 space then the comma then 0 or 1 space.
If there can be tabs also use \s
instead of a space. The \s
will match any kind of space. So :
name = name.replace(/\s*,\s*/, '*');
Upvotes: 2
Reputation: 665456
You can use the \s
whitespace character class repeated multiple times:
name = name.replace(/\s*,\s*/g, '*');
Upvotes: 4