[英]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? 有没有一种使用正则表达式的方法来拾取nodejs中字符串中的最后一个换行位置?
You could use String.prototype.lastIndexOf
您可以使用
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. 与新行不匹配。
JS Code JS代码
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. 在大多数情况下,最后一个换行符可能最接近。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.