将字符串分成两行

时间:2014-06-26 05:11:22

标签: javascript jquery string

我想将一个字符串分成两行,但该行不应该在一半的单词中分成两行。我怎么能这样做?

字符串格式如下:

var words="value.eight.seven.six.five.four.three"

预期输出为:

"value.eight.seven.

six.five.four.three"

4 个答案:

答案 0 :(得分:3)

尝试,

var words = "value.eight.seven.six.five.four.three";
var splitted = words.split('.');
var index = splitted.length / 2;  
var val1 = splitted.slice(0, index).join('.') + ".";
var val2 = splitted.slice(index, splitted.length).join('.');

DEMO

答案 1 :(得分:2)

试试这个:

    var words="value.eight.seven.six.five.four.three"
    var wordsArr = words.split(".");
    var line1 = wordsArr.slice(0,Math.floor(wordsArr.length/2)).join("."); 
    var line2 = wordsArr.slice(Math.floor(wordsArr.length/2)).join(".");

这是工作小提琴:

http://jsfiddle.net/6xgS2/

答案 2 :(得分:1)

您执行以下操作 - >

var words = "value.eight.seven.six.five.four.three";
var all = words.split(".");
var new="";  //empty string

for(var i=0;i<all.length;i++){
new=new+all[i]+".";  //add each word and the .
if(i==3)
new=new+"\n"; //add a \n after the third word
}

新var将包含您的新字符串。 希望这可以帮助。

答案 3 :(得分:0)

试试这个

var words = "value.eight.seven.six.five.four.three";

var all = words.split(".");
var half=all.length/2;
var first = all.slice(0, half).join();
var second = all.slice(half, all.length).join();

DEMO