如何在JavaScript中计算字符串的行数

119

我想要计算一个字符串中的行数。我尝试使用stackoverflow上的这个答案,

lines = str.split("\r\n|\r|\n"); 
return  lines.length;

对于这个字符串(最初是一个缓冲区):

 GET / HTTP/1.1
 Host: localhost:8888
 Connection: keep-alive
 Cache-Control: max-age=0
 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2) AppleWebKit/535.2 (KHTML,like Gecko) Chrome/15.0.874.121 Safari/535.2
 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
 Accept-Encoding: gzip,deflate,sdch
 Accept-Language: en-US,en;q=0.8
 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3

出于某种原因,我得到了lines='1'

有什么办法让它工作吗?


3
@BookOfZeus的正则表达式处理"\n"和"\r","\n\r"是错误的。请注意,不能改变原文的含义。 - bezmax
哦,我明白了,你是对的,我的错。 - Book Of Zeus
我已经回答了一个相关的问题,“测试最少行数或标记的最快方法是什么?” http://stackoverflow.com/questions/39554154/fastest-way-to-test-for-a-minimum-number-of-lines-or-tokens - Joe Lapp
@bezmax:在粘贴文本时,“\n\r”是必要的。 - Supreme Dolphin
@SupremeDolphin 不是的,至少对于给出的示例不是。请参见https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_message:“请求行和其他标题字段必须以<CR><LF>结尾”,即\r\n - bezmax
11个回答

1
 <script type="text/javascript">
      var multilinestr = `
        line 1
        line 2
        line 3
        line 4
        line 5
        line 6`;
      totallines = multilinestr.split("\n");
lines = str.split("\n"); 
console.log(lines.length);
</script>

这在我的情况下有效。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接