I have this JavaScript:
JavaScript
x
7
1
var str = "abcdefoihewfojias".split('');
2
3
for (var i = 0; i < str.length; i++) {
4
var xp = str[i] = "|";
5
}
6
alert( str.join("") );
7
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:
JavaScript
1
8
1
var str = "abcdefoihewfojias".split('');
2
var nth = 4; // the nth character you want to replace
3
var replaceWith = "|" // the character you want to replace the nth value
4
for (var i = nth-1; i < str.length-1; i+=nth) {
5
str[i] = replaceWith;
6
}
7
alert( str.join("") );
8