Skip to content
Advertisement

Replace every nth character from a string

I have this JavaScript:

var str = "abcdefoihewfojias".split('');

for (var i = 0; i < str.length; i++) {
    var xp = str[i] = "|";
}
alert( str.join("") );

I aim to replace every fourth letter in the string abcdefoihewfojias with |, so it becomes abc|efo|....etc,but I do not have a clue how to do this.

Advertisement

Answer

To support re-usability and the option to wrap this in an object/function let’s parameterise it:

var str = "abcdefoihewfojias".split('');
var nth = 4; // the nth character you want to replace
var replaceWith = "|" // the character you want to replace the nth value
for (var i = nth-1; i < str.length-1; i+=nth) {
    str[i] = replaceWith;
}
alert( str.join("") );
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement