gpt4 book ai didi

javascript - 字符串用句号替换多个字符 - Javascript

转载 作者:行者123 更新时间:2023-11-30 21:01:05 25 4
gpt4 key购买 nike

例子:

string = "Lorem ipsum dolor sit amet consectetur adipiscing elit";
indices = [4,7,9,12,15];
output = "Lore* *p*um*do*or sit amet consectetur adipiscing elit";

我想用“*”替换字符 5、8、10、13 和 16。我做了 +1 因为索引包含索引。 我该怎么做?

下面的代码工作正常,但只有 for 循环中的最后一个 replaceAt 保留。我得到:output = "Lorem ipsum do*or sit amet consectetur adipiscing elit";

代码

        var input = "Lorem ipsum dolor sit amet consectetur adipiscing elit";
var indices = [], newIndices = [];
for(var i=0; i<input.length;i++) {
if (input[i] === " ") indices.push(i);
}
var totalIndices = indices.length;

if(totalIndices >= 9){
//new indices array
for(var j=0; j<totalIndices;j+=4) {
//indices.splice(j, 1);
newIndices.push(indices[j]);
}
//Change spaces to full-stop
for(var k=0; k<newIndices;k++) {
input.replaceAt(newIndices[k], ".");
}
}else{
input.split(" ").join('.');
}

最佳答案

您可以迭代索引数组并通过替换索引处的字符来减少拆分的字符串。

var string = "Lorem ipsum dolor sit amet consectetur adipiscing elit",
indices = [4, 7, 9, 12, 15];
result = indices.reduce(function (r, i) {
r[i] = '*';
return r;
}, string.split('')).join('');

console.log(result);

ES6

var string = "Lorem ipsum dolor sit amet consectetur adipiscing elit",
indices = [4, 7, 9, 12, 15];
result = Object.assign([...string], ...indices.map(i => ({ [i]: '*' }))).join('');

console.log(result);

关于javascript - 字符串用句号替换多个字符 - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47136158/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com