-1

我正在尝试使用具有特定量词的字符类创建一个正则表达式,该量词是一个变量,例如:

var str = "1234.00";
var quantifier = 3;
str = str.replace(/(\d)(\d{quantifier}\.)/,"$1,$2");
//str should be "1,234.00"

这工作如下(没有变量):

var str = "1234.00";
str = str.replace(/(\d)(\d{3}\.)/,"$1,$2");
//str == "1,234.00"

但是,它与带引号的模式而不是斜线分隔的模式没有相同的功能,如下所示:

var str = "1234.00";
str = str.replace("(\d)(\d{3}\.)","$1,$2");
//str == "1234.00" - not "1,234.00"
//quote symbol choice does not change this
str = str.replace('(\d)(\d{3}\.)',"$1,$2");
//str == "1234.00" - not "1,234.00"

编辑:为了更清楚,我添加了一个摘要问题,该问题在下面得到了回答: 如何使用带引号的字符串的插值变量创建正则表达式?

虽然我更喜欢使用插值,但它似乎不可用(至少在这种情况下),也没有必要。

我还尝试想出一种方法来连接/加入一些正则表达式文字以达到相同的结果,但对于这个用例却无法这样做。

作为旁注 - 我熟悉 perl 中的这种类型的正则表达式:

my $str = "1234.00";
my $quantifier = 3;
$str =~ s/(\d)(\d{$quantifier}\.)/$1,$2/;
# $str eq "1,234.00"

可以如下使用:

my $str = "1234567890.00";
for my $quantifier (qw(9 6 3)) {
    $str =~ s/(\d)(\d{$quantifier}\.)/$1,$2/;
}
# $str eq "1,234,567,890.00"

根据提供的建议/答案,我创建了一个示例货币字符串原型,如下所示:

String.prototype.toCurrency = function() {
    var copy = parseFloat(this).toFixed(2);
    for (var times = parseInt(copy.length/3); times > 0; times--) {
        var digits = times * 3;
        var re = new RegExp("(\\d)(\\d{" + digits + "}\\.)");
        copy = copy.replace(re,"$1,$2");
    }
    return '$'+copy;
};
str = "1234567890";
str.toCurrency();
// returns "$1,234,567,890.00"
4

3 回答 3

0

In JavaScript, you can't concatenate or interpolate into regex literals, but you can create a regex from a string by using the RegExp constructor:

str = str.replace(new RegExp('(\\d)(\\d{' + quantifier + '}\\.'), "$1,$2");

Note, by the way, that this:

str.replace(..., ...);

has no effect, because replace doesn't modify a string, but rather, it returns a copy of the string with the replacements made. So you need to write this:

str = str.replace(..., ...);

instead.

于 2012-02-24T03:05:02.177 回答
0

There are two problems with this statement:

str.replace("(\d)(\d{3}\.)","$1,$2");

The first is that you are passing a string and not a regular expression object, and the second is that within a string literal the backslash has a special meaning to escape certain things (e.g., "\n" is a newline) so to have an actual backslash in your string literal you need to double it as "\\". Using the RegExp() constructor to create a regex object from a string you get this:

str.replace(new RegExp("(\\d)(\\d{3}\\.)"),"$1,$2");

So from there you can do this:

var quantifier = 3
str = str.replace(new RegExp("(\\d)(\\d{" + quantifier + "}\\.)"),"$1,$2");
于 2012-02-24T03:05:11.977 回答
0

您可以创建一个 RegExp 对象:

var str = "1234.00";
var digits = 2;
var re = new RegExp("(\\d)(\\d{" + digits + "})");
var str2 = str.replace(re,"$1,$2-");

str2将包含1,23-4.00.

工作示例:

请注意,您需要\在字符串中转义,因此\\.

希望这可以帮助。

于 2012-02-24T03:09:44.173 回答