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 will be:
["This is a", "sample string"].
Another e.x.:
"Gorge is nice" => ["Gorge", "is nice"]
Also it will be nice, if the function can get as param the number of elements that I will get as result.
Thanks for the help!
you can split your words by space
e.g.:
and then walk through the array and compare string lengths. As example
it would be nice to know why it has to be only 2 elements, not the amount of words? Are you going for some algorithm? or do you just want to group the least amount of text needed together?
It would be nice to see why you need this.
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
UPDATE
You can try a splitter like