我有字符串:“这是一个示例字符串”,我需要将其拆分为 2 个字符串,而不破坏单词,并且这两个字符串将具有最接近的长度,因此结果将是:
["This is a", "sample string"].
另一个例子:
"Gorge is nice" => ["Gorge", "is nice"]
如果该函数可以获取作为结果的元素数量作为参数,那就太好了。
谢谢您的帮助!
您可以使用indexOf
第二个参数是字符串长度的一半。这样,indexOf
将寻找下一个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
如果我需要将其拆分为 3 或 4 或其他元素怎么办?
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>');
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)