I have string: \"This is a sample string\", and I need to split it to 2 strings, without break the words, and that the two strings will have the closest length, so the result wi
You can use indexOf
with the second parameter as the half of the length of the string. By this, indexOf
will search for the next index of matching string after the provided index.
Demo
var str = "Thisasdfasdfasdfasdfasdf is a sample string",
len = str.length;
var ind = str.indexOf(' ', Math.floor(str.length / 2) - 1);
ind = ind > 0 ? ind : str.lastIndexOf(' ');
var str1 = str.substr(0, ind),
str2 = str.substr(ind);
document.write(str1 + '
' + str2);
UPDATE
what if i will need to split it to 3 or 4 or whatever elements?
function split(str, noOfWords) {
// Set no. of words to 2 by default when nothing is passed
noOfWords = noOfWords || 2;
var len = str.length; // String length
wordLen = Math.floor(len / noOfWords); // Approx. no. of letters in each worrd
var words = [],
temp = '',
counter = 0;
// Split the string by space and iterate over it
str.split(' ').forEach(function(v) {
// Recalculate the new word length
wordLen = Math.floor((len - words.join(' ').length) / (noOfWords - counter));
// Check if word length exceeds
if ((temp + v).length < wordLen) {
temp += ' ' + v;
} else {
// Add words in the array
words.push(temp.trim());
// Increment counter, used for word length calculation
counter++;
temp = v;
}
});
// For the last element
temp.trim() && words.push(temp.trim());
return words;
}
var str = "This is a sample string. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eos quae error ab praesentium, fugit expedita neque ex odio veritatis excepturi, iusto, cupiditate recusandae harum dicta dolore deleniti provident corporis adipisci.";
var words = split(str, 10);
console.log(words);
document.write('' + JSON.stringify(words, 0, 2) + '
');