字符串用fullstop替换多个字符 - Javascript

时间:2017-11-06 11:40:27

标签: javascript

示例:

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保持不变。 我得到:输出=" Lorem ipsum做*或坐下来为aditiscing 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('.');
        }

1 个答案:

答案 0 :(得分:1)

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

&#13;
&#13;
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);
&#13;
&#13;
&#13;

ES6

&#13;
&#13;
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);
&#13;
&#13;
&#13;