5

I want to break a string into two lines, but the line should not break into two, at the half of a word. How can I do this?

The string format is like this:

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

Expected output is:

"value.eight.seven.

six.five.four.three"
10
  • 1
    what is your expected O/P..? What do you mean by two lines..? want to store the split values into two variables.. Commented Jun 26, 2014 at 5:12
  • you want to break string but still don't want to break in two. It is little confusing. Is it that you want to break it in two halfs but words should not break? Commented Jun 26, 2014 at 5:13
  • you have to be more specific. what is the point at which you want to break the string?? Commented Jun 26, 2014 at 5:15
  • Check this out: stackoverflow.com/questions/14484787/wrap-text-in-javascript It is similar to your issue, just need to change the identifier to break the line accordingly. Commented Jun 26, 2014 at 5:15
  • @ Bhushan Kawadkar:i mean the line should not break at middle of "seven", or "six", means it should break after the third word or the fourth word Commented Jun 26, 2014 at 5:16

4 Answers 4

3

Try,

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

Sign up to request clarification or add additional context in comments.

1 Comment

@Rajapraphu : out Of Topic .. check mail da
2

Try this:

    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(".");

Here is the working fiddle:

http://jsfiddle.net/6xgS2/

Comments

1

you do the following-->

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
}

the new var will have your new string. hope this helps.

Comments

0

try this

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

3 Comments

It will work only for the provided string, it's not a general answer, and I think OP is looking for a general solution which will work on any string.
@balachandran - OP ask to break the line you just splited
this edited answer is look like Rajaprabhu posted. Mahana inaki ne maatinada

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.