我开发了一个有点working solution - 它并不完美,但它会找到中间空间并在那里分裂。话虽如此,更好的解决方案可能涉及总字符数以找到最接近 true 中心的空间,或者甚至可能获取整行的宽度并将字符串的容器 CSS 设置为一半那个宽度。但是我除了时间什么都没有……
最终代码
function nth_occurrence (string, char, nth) {
var first_index = string.indexOf(char);
var length_up_to_first_index = first_index + 1;
if (nth == 1) {
return first_index;
} else {
var string_after_first_occurrence = string.slice(length_up_to_first_index);
var next_occurrence = nth_occurrence(string_after_first_occurrence, char, nth - 1);
if (next_occurrence === -1) {
return -1;
} else {
return length_up_to_first_index + next_occurrence;
}
}
}
function splitValue(value, index) {
return value.substring(0, index) + "," + value.substring(index);
}
function evenBreak(myString) {
var count = (myString.match(/ /g) || []).length; //How many spaces are there
var middle = Math.ceil(count/2); //Find the middle one
var middleIndex = nth_occurrence(myString, " ", middle); //Get the index of the middle one
var splitString = splitValue(myString, middleIndex).split(","); //Split the string into two pieces at our middle
myString = splitString[0] + "<br>" + splitString[1].substring(1); //Put it back together with a line break between
return myString;
}
var str = evenBreak("This is our newly split string with a line break in the center!");
alert(str);
我们是如何到达那里的
首先,我们需要找出有多少个空格...
var count = (temp.match(/ /g) || []).length;
现在我们知道有 X 个空格,最中间的可以通过以下方式找到...
var middle = Math.ceil(count/2);
但是我们如何在字符串中找到中间空格的位置呢?这是我从another question 获取的内容...
function nth_occurrence (string, char, nth) {
var first_index = string.indexOf(char);
var length_up_to_first_index = first_index + 1;
if (nth == 1) {
return first_index;
} else {
var string_after_first_occurrence = string.slice(length_up_to_first_index);
var next_occurrence = nth_occurrence(string_after_first_occurrence, char, nth - 1);
if (next_occurrence === -1) {
return -1;
} else {
return length_up_to_first_index + next_occurrence;
}
}
}
好的,所以我们确切地知道要放置换行符的位置。但是我们需要一个函数来做到这一点。我将在那里拆分字符串并在它们之间放置一个换行符,通过使用以下函数...
function splitValue(value, index) {
return value.substring(0, index) + "," + value.substring(index);
}
已知问题
- 这只是拆分一次。它依赖于将字符串分成两半,而不是多次。
- 如果字符集中度不均匀,字符串将不会被完美分割。它只计算空格,不计入总字符数。例如,如果您有以下句子“他是一个搞笑的喜剧演员”,那么最中心空间两侧的字符差异是巨大的。