Split string to two, will have almost same length

2019-03-05 11:03发布

问题:

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!

回答1:

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>');



回答2:

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>



回答3:

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.