How to change a character every n number of characters?
I have a text string,
let string = 'abcdefghijklm'
I want to change every 4 characters the character for a '_'
to get this:
abc_efg_ijk_m
this works for me, but it splits it with '_' and it doesn't exactly replace the fourth character
const addChar = (stringer, charac, number) => {
let strinChar = "";
const long = stringer.length;
for (let i = 0; i < long; i += number) {
if (i + number < long) {
strinChar += stringer.substring(i, i + number) + charac;
} else {
strinChar += stringer.substring(i, long);
}
}
return strinChar;
}
console.log(addChar(string, '_', 4))
output:
abcd_efgh_ijkl_m
and I want this output:
abc_efg_ijk_m
a similar output is this but in the same way I do not get the desired result
string0.match(/.{1,3}/g).join('_');
I have also tried:
let kool = string.match(/.{1,4}/g)
let newArray = []
for(let i=0; i<=kool.length-1; i++){
newArray.push(kool[i].slice(0, -1))
}
console.log(newArray.join('_'));
but I don't get the desired result