简体   繁体   English

JavaScript将新行插入字符串中间的任何空格

[英]JavaScript insert new line to any space in the middle of string

I would like to insert only 1 new line character roughly in the middle of a string: 我只想在字符串中间大致插入1个换行符:

for (var i=0; i<labels.length; i++){
      if (labels[i].length > 30) {
               //The split would occur here 
      }
}

Is there some JS function that does this? 是否有一些JS函数可以做到这一点?

Any ideas? 有任何想法吗?

Edit 编辑

To replace spaces in a string with a new line: 用换行符替换字符串中的空格:

string.replace(/ /g, '\\n');

/ /g refers to a global replace of all spaces found. / /g对找到的所有空间进行全局替换。

Say your string is as follows: 说你的字符串如下:

var string = 'The quick brown fox jumps over the lazy dog';

You need to find the length of the string, the middle point, and the nearest space from the middle: 您需要找到字符串的长度,中间点以及距离中间最近的空格:

var length = string.length;
var middle = Math.round(length / 2);
var spaceNearMiddle = string.indexOf(' ', middle);
var string1 = string.substring(0, spaceNearMiddle);
var string2 = string.substring(spaceNearMiddle + 1, length);

The result of string1 and string2 would be "The quick brown fox" and "jumps over the lazy dog". 字符串1和字符串2的结果将是“快速的棕色狐狸”和“跳过懒狗”。

something like this? 这样的东西?

for (var i=0; i<labels.length; i++){
  if (labels[i].length > 30) {
      var index = labels[i].indexOf(' ', 30);
      var part1 = labels[i].substring(0,30);
      var part2 = labels[i].substring(30);
      if(index != -1){
          labels[i] = part1 + '\n' + part2;
      }

  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM