Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
165
rated 0 times [  168] [ 3]  / answers: 1 / hits: 18228  / 9 Years ago, sun, august 16, 2015, 12:00:00

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.


More From » string

 Answers
27

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() );

[#65404] Wednesday, August 12, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zayne

Total Points: 366
Total Questions: 98
Total Answers: 98

Location: India
Member since Wed, Aug 4, 2021
3 Years ago
;