0

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!

Tushar
  • 85,780
  • 21
  • 159
  • 179
Ziki
  • 1,390
  • 1
  • 13
  • 34
  • You can counting word like this [link](http://stackoverflow.com/questions/18679576/counting-words-in-string) and then split text. – Karim Pazoki Oct 08 '15 at 10:05
  • count words, then split at the half of the total words, in a blank space – mgul Oct 08 '15 at 10:06
  • ziki Check [Demo using substr](https://jsfiddle.net/tusharj/9ub0erLp/) Also, see [using array](https://jsfiddle.net/tusharj/9ub0erLp/1/) – Tushar Oct 08 '15 at 10:07
  • @Tushar both not working with this ex: "Thisasdfasdfasdfasdfasdf is a sample string" – Ziki Oct 08 '15 at 10:13
  • It's incredible that this question has so many answers. It's a trivial problem, and the OP doesn't even say what he have tried and where he has difficulties. – JotaBe Oct 08 '15 at 10:52

3 Answers3

3

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 + ' <br /> ' + 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('<pre>' + JSON.stringify(words, 0, 2) + '</pre>');
Tushar
  • 85,780
  • 21
  • 159
  • 179
  • @ArunPJohny Thanks for pointing out, adding `ind = ind > 0 ? ind : str.lastIndexOf(' ');` will solve the problem – Tushar Oct 08 '15 at 10:30
  • @Tushar what if i will need to split it to 3 or 4 or whatever elements? – Ziki Oct 08 '15 at 10:38
  • 1
    Hey @ArunPJohny, Please check the updated answer, took some time but I've done it! yay!, not perfect but close :) – Tushar Oct 08 '15 at 14:19
1

You can try a splitter like

function split(str) {
  var len = str.length,
    mid = Math.floor(len / 2);

  var left = mid - str.substring(0, mid).lastIndexOf(' '),
    right = str.indexOf(' ', mid) - mid;

  var ind = mid + (left < right ? -left : right);

  return [str.substr(0, ind),
    str2 = str.substr(ind)
  ];
}

var parts = split("123-456 3-5-asldfkjas kdfasdfasd fjas");
snippet.log(parts[0]);
snippet.log(parts[1]);
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
-2

you can split your words by space

e.g.:

var words = 'George is nice'
words = words.split(' ')

and then walk through the array and compare string lengths. As example

var concat = ''
for (var word in words)
{
    word = words[word]
    if (word.length < words[word - 1] )
    {
        concat += word
    }
}

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.

Misan
  • 1
  • I need to save them in two places to show them, but that they will have the ~same length – Ziki Oct 08 '15 at 10:14