Reputation: 8960
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?
Upvotes: 0
Views: 2561
Reputation: 958
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".
Upvotes: 1
Reputation: 10211
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;
}
}
}
Upvotes: 0