Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cut off string after the first line in the paragraph

I have the string as show below:

XXX:Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur cursus lacus sed justo faucibus id pellentesque nunc porttitor. Sed venenatis tempor dui, nec mattis dolor ultrices at. Duis suscipit, dolor sed fringilla interdum, magna libero tempor quam, sed molestie dui urna sed tellus. 

How can I add a restriction and cut the string off at the first line? (using javascript).

The end result I would expect is as follows:

XXX:Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur... 
like image 884
Zhen Avatar asked Dec 08 '11 19:12

Zhen


People also ask

How do you break a line break?

To split a string by newline, call the split() method passing it the following regular expression as parameter - /\r?\ n/ . The split method will split the string on each occurrence of a newline character and return an array containing the substrings.


2 Answers

var firstLine = theString.split('\n')[0]; 
like image 86
Tomalak Avatar answered Sep 30 '22 17:09

Tomalak


Use the optional limit param for increased performance

Tomalak his answer is correct, but in case you want to really only match the first line it will be useful to pass the optional second limit parameter. Like this you prevent that a long string (with thousands of lines) will be splitted till the end before the first match is returned.

With setting the optional limit to 1 we tell the method to return the result as soon as the first match is found with increased performance as a result.

var firstLine = theString.split('\n', 1)[0]; 

Read more on the limit param for example here in the MDN docs

like image 26
Wilt Avatar answered Sep 30 '22 16:09

Wilt