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

时间:2009-11-20 20:07:49

标签: 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.$"

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

9 个答案:

答案 0 :(得分:134)

使用正则表达式

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

The q$uick $brown$ fox $jumps$ over$ the $lazy $dogs.$

欢呼声,

答案 1 :(得分:60)

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

答案 2 :(得分:5)

  

保持简单

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

答案 3 :(得分:1)

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

答案 4 :(得分:1)

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

说明:拆分(&#39;&#39;)将字符串转换为数组。现在我们要将数组转回一个字符串。在这种情况下,减少是完美的。数组的reduce函数有3个参数,第一个是累加器,第二个是迭代元素,第三个是索引。由于数组索引是基于0的,要在第5个之后插入,我们正在查看索引i%5 === 4。

答案 5 :(得分:1)

有时您还想开始从字符串末尾插入字符到开头。在这种情况下,这可能会:

function insert_spaces(string, space_every_nr, reverse, character) {
var insert_string = string.toString();

if (reverse == true) {
    var insert_string = string.toString();
    var length_of_string=string.length;
    var count=0;
    for (var i = 0; i < string.length+count; i+=space_every_nr) {
        insert_string=insert_string.substring(0,i)+character+insert_string.substring(i ,(string.length+count));
        count++;
    }
    return insert_string
} else if(reverse ==false) {
    var count=0;
    var j=0;
    for (var i = string.length; i > 0; i -= space_every_nr) {
        insert_string=insert_string.substring(0,i)+character+insert_string.substring(i ,(string.length+count));
        count++;
    }
    return insert_string;
  }
}

答案 6 :(得分:1)

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

结果:

> addItemEvery("The quick brown fox jumps over the lazy dogs.", '$', 5)
> "The q$uick $brown$ fox $jumps$ over$ the $lazy $dogs."

答案 7 :(得分:0)

我做了类似的事情,为移动应用程序分离了friendCode,但是使用了Arrayreduce

这将需要一个字符串,检查每个n个字符,并在该位置添加定界符。

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

答案 8 :(得分:0)

这是先前的答案之一,但是我将其包装在一个函数中,并且给了它一个“偏移”参数,而不是对其进行硬编码。

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