How can I insert a character after every n characters in javascript?
JavascriptStringJavascript Problem Overview
I have a string: "The quick brown fox jumps over the lazy dogs."
I want to use JavaScript (possibly with jQuery) to insert a character every n characters. For example I want to call:
var s = "The quick brown fox jumps over the lazy dogs.";
var new_s = UpdateString("$",5);
// new_s should equal "The q$uick $brown$ fox $jumps$ over$ the $lazy $dogs.$"
The goal is to use this function to insert into long strings to allow them to wrap.
Maybe someone knows of a better way?
Javascript Solutions
Solution 1 - Javascript
With regex
"The quick brown fox jumps over the lazy dogs.".replace(/(.{5})/g,"$1$")
The q$uick $brown$ fox $jumps$ over$ the $lazy $dogs.$
cheers,
Solution 2 - Javascript
function chunk(str, n) {
var ret = [];
var i;
var len;
for(i = 0, len = str.length; i < len; i += n) {
ret.push(str.substr(i, n))
}
return ret
};
chunk("The quick brown fox jumps over the lazy dogs.", 5).join('$');
// "The q$uick $brown$ fox $jumps$ over$ the $lazy $dogs."
Solution 3 - Javascript
> Keep it simple
var str = "123456789";
var parts = str.match(/.{1,3}/g);
var new_value = parts.join("-"); //returns 123-456-789
Solution 4 - Javascript
let s = 'The quick brown fox jumps over the lazy dogs.';
s.split('').reduce((a, e, i)=> a + e + (i % 5 === 4 ? '$' : ''), '');
Explain: split('') turns a string into an array. Now we want to turn the array back to one single string. Reduce is perfect in this scenario. Array's reduce function takes 3 parameters, first is the accumulator, second is the iterated element, and the third is the index. Since the array index is 0 based, to insert after 5th, we are looking at index i%5 === 4.
Solution 5 - Javascript
var str="ABCDEFGHIJKLMNOPQR";
function formatStr(str, n) {
var a = [], start=0;
while(start<str.length) {
a.push(str.slice(start, start+n));
start+=n;
}
console.log(a.join(" "));
}
formatStr(str,3);
Solution 6 - Javascript
function addItemEvery (str, item, every){
for(let i = 0; i < str.length; i++){
if(!(i % (every + 1))){
str = str.substring(0, i) + item + str.substring(i);
}
}
return str.substring(1);
}
Result:
> addItemEvery("The quick brown fox jumps over the lazy dogs.", '$', 5)
> "The q$uick $brown$ fox $jumps$ over$ the $lazy $dogs."
Solution 7 - Javascript
Here's one of the previous answers, but I wrapped it in a function, and I gave it an "offset" parameter instead of hard coding it.
// https://stackoverflow.com/a/2712896/3480193
addCharToStringEveryXSpots(str, char, offset) {
if ( ! char ) {
return str;
}
let regExPattern = new RegExp('(.{' + offset + '})', 'g');
return str.replace(regExPattern, '$1' + char);
};
Solution 8 - Javascript
I did something similar to separate a friendCode
for a mobile app but using Array and reduce.
This will take a string, check every n
characters and add delimiter at that location.
/**
* A function to easily inject characters every 'n' spaces
* @param {string} friendCode The string we want to inject characters in
* @param {*} numDigits Determines the 'n' spaces we want to inject at
* @param {*} delimiter The character(s) we want to inject
*/
function formatFriendCode(friendCode, numDigits, delimiter) {
return Array.from(friendCode).reduce((accum, cur, idx) => {
return accum += (idx + 1) % numDigits === 0 ? cur + delimiter : cur;
}, '')
}
formatFriendCode("000011112222", 4, ' ')
// output "0000 1111 2222 "
formatFriendCode("The quick brown fox jumps over the lazy dogs.", 5, '$')
// output "The q$uick $brown$ fox $jumps$ over$ the $lazy $dogs.$"