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

bre*_*dan 63 javascript string

我有一根绳子:"快速的棕色狐狸跳过懒狗."

我想使用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.$"
Run Code Online (Sandbox Code Playgroud)

目标是使用此函数插入并调整长字符串以允许它们换行.也许有人知道更好的方法?

YOU*_*YOU 148

用正则表达式

"The quick brown fox jumps over the lazy dogs.".replace(/(.{5})/g,"$1$")

The q$uick $brown$ fox $jumps$ over$ the $lazy $dogs.$
Run Code Online (Sandbox Code Playgroud)

干杯,

  • 该死的!那里有很好的正则表达式.BTW是替换字符串中需要的最后一个`$`? (9认同)
  • 我到了``string'.replace(/.{5}/g,"$&"+"<br>");`.最后的连接只是为了使它更容易阅读.替换中的`$&`匹配匹配的字符串,因此不需要分组. (5认同)
  • 从字符串的末尾开始计算时,它会如何工作? (3认同)
  • 替换字符串中的最后一个**$**不需要,您可以在此处放置5个空格间隔的内容,例如**<br>**. (2认同)

Cre*_*esh 64

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."
Run Code Online (Sandbox Code Playgroud)

  • +1,但你的分号有点开关;) (6认同)

Kar*_*eem 14

把事情简单化

  var str = "123456789";
  var chuncks = str.match(/.{1,3}/g);
  var new_value = chuncks.join("-"); //returns 123-456-789
Run Code Online (Sandbox Code Playgroud)

  • "123-456-789-0".replace(/-([^-]+)$/, '$1'); //删除最后一个破折号 (2认同)

g.s*_*sui 5

let s = 'The quick brown fox jumps over the lazy dogs.';
s.split('').reduce((a, e, i)=> a + e + (i % 5 === 4 ? '$' : ''), '');
Run Code Online (Sandbox Code Playgroud)

说明:split('')把一个字符串变成一个数组。现在我们要将数组转回单个字符串。在这种情况下,Reduce是完美的。Array的reduce函数有3个参数,第一个是累加器,第二个是迭代元素,第三个是索引。由于数组索引是基于 0 的,要在第 5 个之后插入,我们正在查看索引 i%5 === 4。