将字符串拆分为两个,将具有几乎相同的长度

时间:2015-10-08 09:59:25

标签: javascript string split string-length

我有字符串:"这是一个示例字符串",我需要将其拆分为2个字符串,不会破坏单词,并且两个字符串将具有最接近的长度,因此结果将是:

["This is a", "sample string"].

另一个e.x。:

"Gorge is nice" => ["Gorge", "is nice"]

如果函数可以作为参数获得我将得到的元素数量,那么它也会很好。

感谢您的帮助!

3 个答案:

答案 0 :(得分:3)

您可以将indexOf与第二个参数一起用作字符串长度的一半。这样,indexOf将在提供的索引之后搜索匹配字符串的下一个索引

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);
&#13;
&#13;
&#13;

<强>更新

  

如果我需要将它拆分为3或4或其他任何元素怎么办?

&#13;
&#13;
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>');
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以尝试像

这样的分割器

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>

答案 2 :(得分:-2)

你可以按空格分割你的单词

例如:

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

然后遍历数组并比较字符串长度。 例如

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

很高兴知道它为什么只有2个元素,而不是单词的数量? 你想要一些算法吗?或者你只是想将最少量的文本分组在一起?

很高兴看到你为什么需要这个。