猿问

如何在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.$"

目的是使用此函数将&shy插入长字符串以允许它们进行换行。也许有人知道更好的方法?


一只萌萌小番薯
浏览 1707回答 3
3回答

慕田峪9158850

function chunk(str, n) {&nbsp; &nbsp; var ret = [];&nbsp; &nbsp; var i;&nbsp; &nbsp; var len;&nbsp; &nbsp; for(i = 0, len = str.length; i < len; i += n) {&nbsp; &nbsp; &nbsp; &nbsp;ret.push(str.substr(i, n))&nbsp; &nbsp; }&nbsp; &nbsp; return ret};chunk("The quick brown fox jumps over the lazy dogs.", 5).join('$');// "The q$uick $brown$ fox $jumps$ over$ the $lazy $dogs."

鸿蒙传说

与正则表达式"The quick brown fox jumps over the lazy dogs.".replace(/(.{5})/g,"$1$")The q$uick $brown$ fox $jumps$ over$ the $lazy $dogs.$干杯,

MMMHUHU

把事情简单化&nbsp; var str = "123456789";&nbsp; var chuncks = str.match(/.{1,3}/g);&nbsp; var new_value = chuncks.join("-"); //returns 123-456-789
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答