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

javascript - Regexp: Removing commas from numbers in text - Stack Overflow

programmeradmin0浏览0评论

I want to remove mas from numbers in a text, and I have the following:

/\d\u002c\d/

But this didnt work, and I'm not sure why (looking for a number, a ma, then a number). Overall, I want to detect: (number) km, so that I'll convert it to meters. With the help of others, this is what I have for detecting a number (works on decimals):

/\b(\d+(?:\.\d+)?)+ *km/gi

Is it easier to modify the above or should I first remove the mas from all numbers?

Many thanks in advance!

I want to remove mas from numbers in a text, and I have the following:

/\d\u002c\d/

But this didnt work, and I'm not sure why (looking for a number, a ma, then a number). Overall, I want to detect: (number) km, so that I'll convert it to meters. With the help of others, this is what I have for detecting a number (works on decimals):

/\b(\d+(?:\.\d+)?)+ *km/gi

Is it easier to modify the above or should I first remove the mas from all numbers?

Many thanks in advance!

Share Improve this question asked May 20, 2014 at 7:13 tj56tj56 1621 gold badge4 silver badges12 bronze badges 7
  • 9 Provide your input and expected output. – anubhava Commented May 20, 2014 at 7:15
  • If I have the following in the text, I want to detect it: 124,000 km (I'm doing the rest of the replacement part in my code, I just want to learn how to detect this specific pattern) I want the number as 124000, so that I'll process it. Thanks! – tj56 Commented May 20, 2014 at 7:20
  • Why not use \d,\d regex for replace? – anubhava Commented May 20, 2014 at 7:21
  • But the number might contain more than one ma, such as 124,123,515 Will this work as well? – tj56 Commented May 20, 2014 at 7:23
  • Yes you can do: input.replace(/(\d),(?=\d)/g, '$1'); – anubhava Commented May 20, 2014 at 7:25
 |  Show 2 more ments

4 Answers 4

Reset to default 4

A way to go is to match the parts around the ma and then remove it:

var input = '124,000 km';
input.replace(/(\d+),(\d+\s?km)/g, '$1$2');

For a trimmed list of numbers each on its own line, this works for me:

(\d*),(\d+)/($1)($2)

Note that the global flag should be active so that the regex keeps on going if there are multiple groups of ma separated digits.

For these values:

1
10
100
1000
1,000
10,000
10000
1,200,000,000,000,999

the regex yields

1
10
100
1000
1000
10000
10000
1200000000000999

Tested here.

In my case I needed to remove mas from numbers only. but must not remove mas which are placed next to a letter. The proper way to solve this is with regex lookarounds:

r'(?<=\d)(,)(?=\d)'

input: "1,2,3,4" -> output: "1234"
input: "1,20,30 F,40" -> output: "12030 F,40"
input: "1,20,30 40,F" -> output: "12030 40,F"
input: "99,20, bla" -> output: "9920, bla"
input: "abc12,34efg" -> output: "abc1234efg"

var str = "124,000";
console.log(str.replace(',', ''));
发布评论

评论列表(0)

  1. 暂无评论