我一直在努力解决这个挑战(在 jschallenger.com 上找到):
这是我到目前为止的解决方案(我确信会起作用):
function insertEveryThree(a, b) {
let arr = a.split('')
for (let i = arr.length - 3; i > 0; i -= 3) {
arr.splice(i, 0, b)
}
return arr.join('')
}
console.log(insertEveryThree('actionable', '-')) // a-cti-ona-ble
console.log(insertEveryThree('1234567', '.')) // 1.234.567
console.log(insertEveryThree('abcde', '$')) // ab$cde
console.log(insertEveryThree('zxyzxyzxyzxyzxyz', 'w')) // zwxyzwxyzwxyzwxyzwxyz
我哪里失败了?
您可以用正则表达式替换字符串。
function insertEveryThree(a, b) {
return a.replace(/(?=(...)+$)/g, b);
}
console.log(insertEveryThree('actionable', '-')) // a-cti-ona-ble
console.log(insertEveryThree('1234567', '.')) // 1.234.567
console.log(insertEveryThree('abcde', '$')) // ab$cde
console.log(insertEveryThree('zxyzxyzxyzxyzxyz', 'w')) // zwxyzwxyzwxyzwxyzwxyz
您需要推入一个新数组,拼接会改变数组并导致索引出现问题:
function insertEveryThree(str, character, index = 3) {
const strArr = str.split("");
const newArr = [];
for (const i = 0; i < str.length; i++) {
newArr.push(strArr[i]);
if ((i + 1) % index === 0 && i !== 0 && i + 1 < str.length) {
newArr.push(character);
}
}
return newArr.join("");
}
console.log(insertEveryThree("actionable", "-")); // act-ion-abl-e
console.log(insertEveryThree("1234567", ".")); // 123.456.7
console.log(insertEveryThree("abcde", "$")); // abc$de
console.log(insertEveryThree("zxyzxyzxyzxyzxyz", "w")); // zxywzxywzxywzxywzxywz
function myFunction(a, b) {
let result = [];
let rest = a;
while (rest.length) {
result.push(rest.slice(-3));
rest = rest.slice(0, -3);
}
return result.reverse().join(b);
}
const str1 = 'Helloworldhowareyou';
const str2 = 'z';
function insertChar(a,b,index){
const c = a.split('');
for(let i=index-1;i<=c.length;i+=index){
c.splice(i, 0, b);
}
return c.join('');
}
console.log(insertChar(str1, str2, 5));
这是我的解决方案,它适用于动态值;