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
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
Share Improve this question asked Mar 14, 2013 at 18:27 JeffJeff 1,8008 gold badges31 silver badges54 bronze badges 03 Answers
Reset to default 4You can use the \s
whitespace character class repeated multiple times:
name = name.replace(/\s*,\s*/g, '*');
Try this following?
name = name.replace(/\s*,\s*/, '*');
@Bergi's answer also adds the g
flag to catch all mas (with whitespace), so depending on your input, that may work as well.
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 ma 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*/, '*');