简体   繁体   中英

How to split break line in javascript?

I have a question about my javascript.

i have something retrieved from my DB like this:

lots of texts in line 1 
lots of texts in line 2
lots of texts in line 3 
lots of texts in line 4

I want to create an array and create elements based on the breakline.

I have something like

var contents = obj.string //obj.string contains the contents above.
contents = contents.split(/(\r\n|\r|\n)/g)

It created more than 4 elements because some elements are just a ' breakline '.

Can anyone help me to get just 4 elements? Thanks so much!

This might not be an elegant solution but you can sanitise the strings by replacing any \\r with \\n and then trim off the last \\n (which will give you an empty array that you do not need).

See example:

var a = "a\nb\rc\n\n\n\n",
    b = a.replace(/\r/g,"\n").replace(/[\n]+/g,"\n").replace(/\n$/,"").split("\n");

output of var a :

"a
 bc



 "

output of var b :

["a", "b", "c"]

The process of cleaning up is as follows:

  1. Take the string and replace all \\r with \\n , this will leave you with multiple \\n in certain places
  2. Clean multiple instances of \\n to singulars
  3. Remove any trailing \\n to avoid an empty array element at the end
  4. Split to array on the \\n

Implicit in your question are two assumptions. First, I assume that the line breaks may be indicated by either '\\r\\n' , '\\n' or '\\r' . Second, you want to ignore empty lines in your result.

I think you can acheive both by first converting all the line breaks into a single form, then splitting while ignoring empty lines, like this:

contents.replace(/(\r\n)|\r|\n/g, '\n').split(/\n+/g)

The replace command should convert all the different line breaks to '\\n' , while the split will split the line wherever it sees 1 or more consecutive '\\n' s.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM