假设我有两个字符串变量:
a = 'LOVE';
b = '....';
Run Code Online (Sandbox Code Playgroud)
我如何使用正则表达式(或其他最快的)来组合a + b来制作:
c = 'L.O.V.E.';
Run Code Online (Sandbox Code Playgroud)
在我的情况下,两个字符串总是长4个字符,第二个字符串不是固定字符,我只是使它成为一个点,使其在屏幕上看起来更清晰.
Moh*_*waj 10
您可以简单地循环遍历较长的字符串,并在每次迭代中将两个字符串中的一个字符追加到结果字符串中.我认为你不需要任何正则表达式:
a = 'LOVE';
b = '....';
var combinedString = '';
var largerLength = Math.max( a.length, b.length );
for( var i = 0; i < largerLength; i++ )
{
combinedString += a.charAt(i) + b.charAt(i);
}//for()
console.log( combinedString );
Run Code Online (Sandbox Code Playgroud)
上面的代码适用于任何长度的字符串.如果你事先知道两个字符串都是4个字符长,我认为最快和最有效的方法是:
a = 'LOVE';
b = '....';
var combinedString = a.charAt[0] + b.charAt[0] + a.charAt[1] + b.charAt[1] + a.charAt[2] + b.charAt[2] + a.charAt[3] + b.charAt[3];
console.log( combinedString );
Run Code Online (Sandbox Code Playgroud)
你可以用Array#reduce它
var a = 'LOVE',
b = '....';
c = a.split('').reduce(function (r, v, i) {
return r + v + b[i];
}, '');
console.log(c);Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
151 次 |
| 最近记录: |