我需要将一串数字分成三 block ,但我不能让一个 block 只包含一个数字,它必须至少包含两个。
例如
[123],[456],[7]
- 这是 Not Acceptable ,因为 7
是独立存在的
[123],[45],[67]
- 这是可接受的解决方案
我快完成了,但我不确定如何处理以确保至少有两位数字。
这是我的解决方案,它将字符串分成三部分但不考虑最小位数:
function solution(s) {
var number = s.replace(/\D/g, '');
number = number.match(/.{1,3}/g); // breaks down into threes
number = number.join('-');
return number;
}
这是一个代码笔,可以看到它的实际效果:http://codepen.io/franhaselden/pen/mPobNb
最佳答案
您可以使用带前瞻性的正则表达式。
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{2,3}(?=..)/g, '$&-');
}
document.write(format(123456789) + '<br>');
document.write(format(12345678901) + '<br>');
document.write(format(1234567) + '<br>');
编辑
虽然我没有发现通过数组进行额外循环是必要的,但此提议为您提供了 String#match()
所需的步骤,以便稍后使用以下正则表达式加入数组:
/.{2,3}(?=..)|.+/g
1st
Alternative:.{2,3}(?=..)
.{2,3}
matches any character (except newline)
Quantifier:
{2,3}
Between2
and3
times, as many times as possible, giving back as needed[greedy]
(?=..)
Positive Lookahead - Assert that the regex below can be matched
.
matches any character (except newline)
.
matches any character (except newline)
2nd
Alternative:.+
.+
matches any character (except newline)
Quantifier:
+
Betweenone
andunlimited
times, as many times as possible, giving back as needed[greedy]
g modifier
: global. All matches (don't return on first match)
var a, i, s = '';
for (i = 1; i < 10; i++) {
s += i;
a = s.match(/.{2,3}(?=..)|.+/g);
document.write(a.join('-') + '<br>');
}
关于javascript - 将字符串分成三 block ,但最少为两 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37134479/