简体   繁体   English

在字符串中获取最后一个换行符的最有效方法是什么

[英]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. 与新行不匹配。

Ideone Demo Ideone演示

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.

相关问题 将字符串转换为数字的最有效方法是什么? - What is the most efficient way to convert a string to a number? 获取朋友在Facebook(json)上分享的最新视频的最有效方法是什么? - what would be the most efficient way to get the last videos my friends share on facebook (json)? 使用JavaScript评估字符串是否是回文符的最有效方法是什么? - What's the most efficient way to evaluate if a string is a palindrome using Javascript? 在Java中通过字符串的最有效方式是什么? - What is the most efficient way to go through string's chars in Javascript? 拆分字符串并确保结果数组中没有重复项的最有效方法是什么? - What is the most efficient way of splitting a string and ensuring there are no duplicates in the resulting array? 在字符串中查找常用词的最有效方法是什么[暂停] - What is the most efficient way to find the common words in a String [on hold] 在数组中获取最高和最低值的最有效方法是什么 - What is the most efficient way to get the highest and the lowest values in a Array 获取 SQL 表值的最有效方法是什么? - What is the most efficient way to get SQL table values? Javascript:获得零下限的最有效方法是什么? - Javascript: what is the most efficient way to get a lower bound of zero? 从数组中获取具有最高优先级的字符串的最有效方法 - Most efficient way to get the string with highest priority out of an array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM