TypeScript 字符串替换为正则表达式、组和部分字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45699571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:49:15  来源:igfitidea点击:

TypeScript string replace with regex, groups and partial string

regextypescriptreplace

提问by Rafael

I want to use regex to format a number inside an input as I type it.
My problem is: Since I'm using groups to format the number, it only formats when the string matches the regex. Here's an example:
The full number is: 12312312312| Formatted would look like: 123.123.123-12.

我想在输入时使用正则表达式来格式化输入中的数字。
我的问题是:由于我使用组来格式化数字,因此它仅在字符串与正则表达式匹配时进行格式化。这是一个例子:
完整的数字是:12312312312| 格式化后看起来像:123.123.123-12.

If I type 1231231for example, it doesn't formats to 123.123.1as I was expecting, only if I type the entire number.

1231231例如,如果我输入,它不会123.123.1按照我的预期格式化,只有当我输入整个数字时。

This is my function:

这是我的功能:

format(value){
    // This function returns the formatted string on user input
    return value.replace(/(\d{3})(\d{3})(\d{3})(\d+)/, "$1.$2.$3-$4");
}

Is there any way to make the remaining groups optionals?

有什么办法可以让剩余的组成为可选项?

回答by marvel308

You can do it using

你可以使用

function formatStr(str){
  str = str.replace(/(\d{1,3})(\d{0,3})(\d{0,3})(\d{0,2})/g, function(a, b, c, d, e){
        let ret = "";
        if(b != "")
            ret = b;
        if(c != "")
            ret = ret+"." + c;
        if(d != "")
            ret = ret+"." + d;
        if(e != "")
            ret = ret+"-" + e;
        return ret;
  })
  console.log(str);
}

formatStr('12312312312');
formatStr('1231231');

回答by anubhava

You can use this formatfunction with 2 calls to .replace:

您可以format通过 2 次调用使用此函数.replace

  1. First we insert a dot after every 3 digits
  2. Second we replace 3rd dot with hyphen
  1. 首先我们在每 3 位数字后插入一个点
  2. 其次,我们用连字符替换第三个点

Code:

代码:

function format(value) {
    // This function returns the formatted string on user input
    return value.replace(/(\d{3})/g, '.')
                .replace(/((?:\d{3}\.){2}\d{3})\./, '-');
}

console.log(format('1231231'));  //=> 123.123.1
console.log(format('12312312312')); //=> 123.123.123-12