简体   繁体   中英

What is the most efficient way to get the last line break in a string

I have the following function to get the last line break position in a string:

function getLastLineBreak (content) {
    function reverse(s){
        return s.split("").reverse().join("")
    }
    var reversed = reverse(content)
    var index = content.length-reversed.indexOf("\n")
    return index
}

var myString = "some text \n next linet \n another link \n 123"
indexIs = getLastLineBreak(myString)
console.log("index is", indexIs)
console.log("text after", indexIs, myString.substr(indexIs,myString.length))

Is there a way using regular expression to pick up the last line break position within the string in nodejs?

You could use String.prototype.lastIndexOf

 var myString = "some text \\n next linet \\n another link \\n 123"; document.write(myString.lastIndexOf('\\n')); 

This should also work

(.*$)

We can take advantage of the fact that . do not matches new line.

Ideone Demo

JS Code

 var re = /(.*$)/g; var str = 'some text \\n next linet \\n another link \\n 123'; matches = re.exec(str); document.writeln(matches[1]) 

I would do it the old fashioned way. /(\\r?\\n)[^\\r\\n]*$/

This should start from the end of the string and work backwards.
Where the last linebreak is probably closest in most cases.

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