我有一个 16 位数字的属性,例如 (1234123412341234)。我希望它在我的 UI 上呈现,例如每 4 个数字字符一个空格(1234 1234 1234 1234)。我正在使用 Angular JS,所以我正在寻找一种方法来完成此任务。我很确定它要么是自定义的 Angular 过滤器,要么是与正则表达式相关,但我对其中任何一个以及如何实现它的了解都是有限的。
最佳答案
您可以使用带有前瞻功能的正则表达式。
Positive Lookahead查找等号后面的模式,但不将其包含在匹配中。
x(?=y)
Matches 'x' only if 'x' is followed by 'y'. This is called a lookahead.
For example,
/Jack(?=Sprat)/
matches 'Jack' only if it is followed by 'Sprat'./Jack(?=Sprat|Frost)/
matches 'Jack' only if it is followed by 'Sprat' or 'Frost'. However, neither 'Sprat' nor 'Frost' is part of the match results.
function format(s) {
return s.toString().replace(/\d{4}(?=.)/g, '$& ');
}
console.log(format(1234123412341234));
关于javascript - 如何在 UI 中渲染一个数字,每 4 个字符后有一个空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52205639/