简体   繁体   中英

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:

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?

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.

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

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

  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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