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

javascript - Regex replace a set of characters - Stack Overflow

programmeradmin5浏览0评论

I want to replace + - ( ) and space with an empty character in a Javascript string. The expression I'm using is:

"+1 - (042) - 123456".replace(/[\+\-\' '\(\)]/, "");

which results in:

"1 - (042) - 123456"

Only the + is replaced and not the other characters. What is the error in my expression?

I want to replace + - ( ) and space with an empty character in a Javascript string. The expression I'm using is:

"+1 - (042) - 123456".replace(/[\+\-\' '\(\)]/, "");

which results in:

"1 - (042) - 123456"

Only the + is replaced and not the other characters. What is the error in my expression?

Share Improve this question edited Jul 11, 2015 at 9:00 georg 215k56 gold badges322 silver badges400 bronze badges asked Jul 11, 2015 at 8:55 Amal AntonyAmal Antony 6,86715 gold badges54 silver badges77 bronze badges 2
  • 1 Most characters in a class don't need escaping: [-+'() ] – georg Commented Jul 11, 2015 at 9:01
  • 1 Note that if you want to strip out all non-digits could use \D the negation of \d which is a short for [0-9]: Replace /\D+/g with empty string (besides the reason why it failed which is answered already). – Jonny 5 Commented Jul 11, 2015 at 11:01
Add a ment  | 

4 Answers 4

Reset to default 5

When you use square brackets to list characters to remove/change or whatever, you don't want to escape them. And I would remend using \s instead of , and, of course, you need the global flag - g.

"+1 - (042) - 123456".replace(/[+()\s-]/g, "")

Use the g flag:

/[\+\-\' '\(\)]/g

JS:

"+1 - (042) - 123456".replace(/[\+\-\' '\(\)]/g, "");

The g indicates a "Global search", meaning that every match of the regex must be replaced.

You need to include g global flag inorder to make pattern to match two or more times on the same line. And alo you don't need to include single quotes inside the character class.

"+1 - (042) - 123456".replace(/[-+() ]/g, "");

As idmean mentioned in their answer , you should add the g(global) flag , otherwise the function will stop once the first match is found .

However , there are some redundant escapes and characters in your RegEx.

That's how your RegEx can be in its simplest form :

/[+) (-]/g

I didn't get why there are single quotes in your RegEx.

发布评论

评论列表(0)

  1. 暂无评论