如何在javascript中每n个字符后插入一个字符? [英] How can I insert a character after every n characters in javascript?

查看:95
本文介绍了如何在javascript中每n个字符后插入一个字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串:快速的棕色狐狸跳过懒狗。

I have a string: "The quick brown fox jumps over the lazy dogs."

我想用javascript(可能用jQuery)来插入一个字符 n 个字符。例如,我想打电话:

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 &shy into long strings to allow them to wrap. Maybe someone knows of a better way?

推荐答案

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

这篇关于如何在javascript中每n个字符后插入一个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆