Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 865
Cat Overlord Avatar asked Sep 20 '25 13:09

Cat Overlord


2 Answers

You could just do it with a regex replace:

var str = "abcdefoihewfojias";
    
var result = str.replace(/(...)./g, "$1|");

console.log(result);
like image 168
James Montagne Avatar answered Sep 23 '25 02:09

James Montagne


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("") );
like image 37
user2723025 Avatar answered Sep 23 '25 01:09

user2723025