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 ev
Solution 1:
You could just do it with a regex replace:
var str = "abcdefoihewfojias";
var result = str.replace(/(...)./g, "$1|");
console.log(result);
Solution 2:
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("") );
Solution 3:
This might help you solve your problem
var str = "abcdefoihewfojias".split("");
for (var i = 3; i < str.length - 1; i+=4) {
str[i] = "|";
}
alert( str.join("") );
You go with for loop from the the first char that you want to replace (the 3 char) until the one digit before the end and replace every 4 places.
If the for loop will go from the str.length and not to str.length-1 sometimes at the last char will be |.
Solution 4:
Simple just use modulus
https://jsfiddle.net/ctfsorwg/
var str = "abcdefoihewfojias";
var outputStr = str.split("");
for (var i = 0; i < outputStr.length; i++) {
if(!((i+1)%4))outputStr[i] = '|';
}
alert( "Before: " + str + "\nAfter: " + outputStr.join(""));
Solution 5:
.map one-liner
You can use this one-liner:
var str = "abcdefoihewfojias";
str.split('').map(function(l,i) {
return (i + 1) % 4 ? l : '|';
}).join('');
%
returns the remainder. So:
# | Result (# + 1) % 4
---|-------
0 | 1
1 | 2
2 | 3
4 | 0 // Bingo!
ES6 alternative
With ES6, you can do:
[...str].map((l,i) => (i + 1) % 4 ? l : '|')
Post a Comment for "Replace Every Nth Character From A String"