javascript - 如何在javascript中的N个字符数后插入新行?

标签 javascript jquery algorithm

我有一个字符串,其中可能有新行 '\n' 字符。现在我想在该字符串中每 4 个(或 N 个)字符后插入新行 '\n'。

例如:

1) 输入:“我是 John Doe。”

输出:“我是\nJohn\nDoe”

在上面的例子中,在包含空格的 4 个字符后插入 '\n'

2) 输入:“我\nam John Doe”

输出:“我\nam J\nohn\nDoe”

在上面的例子中,在第一个 '\n' 已经存在于字符串中之后的 4 个字符之后插入空格

3) 输入:12345\n67890

输出:1234\n5\n6789\n0

4) 输入:“1234\n56\n78901”

输出:“1234\n56\n7890\n1”

到目前为止,我已经创建了一个函数,它在每 4 个字符后插入 '\n' 但它不会考虑 '\n' 如果它已经存在于原始字符串中。

function addNewlines(str) {
  if (str.length >= 4) {
    var result = '';
    while (str.length > 0) {
      result += str.substring(0, 4) + '\n';
      str = str.substring(4);
    }
    return result;
  }
  return str;
}

我在每次按键时调用此函数并传递原始字符串并获取输出并进一步使用它。我希望你明白我在这里想说的意思。它应该保留之前插入的新行。

让我知道我可以进一步解释。有更多的例子。

最佳答案

以下是我对要求的最佳猜测:

function addNewLines (str) { 
      return str.replace (/(?!$|\n)([^\n]{4}(?!\n))/g, '$1\n');
}

一些测试字符串及其结果:

 "I am John Doe.",   -> "I am\n Joh\nn Do\ne."
 "I\nam John Doe",   -> "I\nam J\nohn \nDoe"
 "12345\n67890",     -> "1234\n5\n6789\n0"
 "1234\n56\n78901",  -> "1234\n56\n7890\n1"
 "ABCD\nEFGH\nIJKL", -> "ABCD\nEFGH\nIJKL\n"
 "1234",             -> "1234\n"
 "12341234"          -> "1234\n1234\n"

对于那些对正则表达式感到神秘的人,这里有一个分割:

   ---------------------------- (?!     Check that following character(s) are not                  
   |  -------------------------   $|\n  Beginning of string or a newline character                   
   |  |   --------------------- )                
   |  |  | -------------------- (       Start of capture group 1        
   |  |  ||  ------------------   [^\n] Any single character other than newline           
   |  |  ||  |   --------------   {4}   Previous element repeated exactly 4 times        
   |  |  ||  |   |  -----------   (?!   Check that following character(s) are not  
   |  |  ||  |   |  | ---------     \n  a newline    
   |  |  ||  |   |  | | -------   )     
   |  |  ||  |   |  | | |------ )       End of capture group 1  
   |  |  ||  |   |  | | || ---- /g      in replace causes all matches to be processed
   |  |  ||  |   |  | | || |
 /(?!$|\n)([^\n]{4}(?!\n))/g

关于javascript - 如何在javascript中的N个字符数后插入新行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16632436/

相关文章:

javascript - CKEditor激活时如何显示占位符

javascript代码受html页面中文本位置的限制

javascript - 让弹出窗口只出现一次

algorithm - 优化数据结构实现

algorithm - 将排名排列索引到其他排名排列

java - 验证骰子组合

javascript - jQuery Packery 插件没有正确设置高度

javascript - MongoDB 条件聚合在 Meteor 1.4.x 中可用吗?

PHP 数组到 jQuery 选项

javascript - Angular 复选框不独立