最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - regex replace comma - Stack Overflow

programmeradmin2浏览0评论

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 0
Add a ment  | 

3 Answers 3

Reset to default 4

You 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*/, '*');
发布评论

评论列表(0)

  1. 暂无评论