如何在 javascript 中的每 n 个字符之后插入一个字符?

我有一根绳子: “敏捷的棕色狐狸跳过懒惰的狗”

我希望使用 JavaScript (可能使用 jQuery)在每个 N字符中插入一个字符。例如,我想打电话给:

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.$"

我们的目标是使用这个函数将 & 害羞插入到长字符串中,以允许它们进行换行。

也许有人知道更好的办法?

121427 次浏览
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."

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,

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

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."

Keep it simple

  var str = "123456789";
var parts = str.match(/.{1,3}/g);
var new_value = parts.join("-"); //returns 123-456-789

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.$"

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