首页 > 解决方案 > Remove every character from a string except the numbers and characters between them

问题描述

The problem I'm facing is that I'm unable to get number from a string along with dot or comma between those numbers.

Example string: 'kr.2.000,00 DKK' OR '$150.65 USD' OR '€340.00 EUR'

From this string I need to fetch '2.000,00' using regex. so basically the regex would be to fetch numbers and any character that is between them and store them in a variable.

This is my code:

var oldPrice = 'kr.2.000,00 DKK';
var newPrice = oldPrice.replace(/^\d+(\.|,)?\d+(\.|,)?\d+$/igm, "");

I need 2.00,00 in variable newPrice. Please help guys!

标签: javascriptjqueryregex

解决方案


您的模式在正确的轨道上,您只需要删除^$锚点即可使其工作。然后,在您的输入字符串上重复应用它以提取您想要的值。请注意,我对模式所做的一项更改是允许初始数字之后的分隔符/数字部分重复任意次数。这涵盖了一个输入,例如1,500,000,它有超过一千个分隔符。

var re = /\d+(?:[,.]?\d+)*[,.]?\d+/g;
var input = "kr.2.000,00 DKK' OR '$150.65 USD' OR '€340.00 EUR OR ¥1,500,000";
var m;

do {
    m = re.exec(input);
    if (m) {
        console.log(m[0]);
    }
} while (m);


推荐阅读