简体   繁体   中英

Split string at specific number of line

I'm using this code to count how many lines my paragraph have.

const lines = str.split(/\r\n|\r|\n/).length

and lines is 42 in my case, which is fine.

My question is how to split this string into two strings at a specific line.

For example, I want to split string at the fifth line.

I want to show first 5 lines and want to hide rest of lines.

How I can do that ?

Calling const lines = str.split(/\\r\\n|\\r|\\n/); will make lines an array of all the lines you have. Then you can use slice to grab parts of that array. https://www.w3schools.com/jsref/jsref_slice_array.asp

So like:

const firstFiveLines = lines.slice(0,4);

At this point, you have an array of the first 5 lines, but if you want to show those, then you will need additional code to output those lines into the document.

Maybe something like this

Match first 3 lines.

str = `line1
line2
line3
line4
line5
`
str.match(/^(.+?\n){3}/gi)[0]

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