简体   繁体   English

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

[英]How to count the number of lines of a string in javascript

I want to count the number of lines in a string我想计算字符串中的行数

i tried to use this stackoverflow answer :我尝试使用这个 stackoverflow 答案:

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

on this string(which was originally a buffer):在这个字符串(它最初是一个缓冲区)上:

 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

and for some reason i got lines='1'.出于某种原因,我得到了lines='1'。

any idea how to make it work?知道如何使它工作吗?

Using a regular expression you can count the number of lines as使用正则表达式,您可以将行数计算为

 str.split(/\r\n|\r|\n/).length

Alternately you can try split method as below.或者,您可以尝试如下拆分方法。

var lines = $("#ptest").val().split("\n");  
alert(lines.length);

working solution: http://jsfiddle.net/C8CaX/工作解决方案: http : //jsfiddle.net/C8CaX/

另一个简短的,可能比拆分性能更高的解决方案是:

const lines = (str.match(/\n/g) || '').length + 1

要使用正则表达式进行拆分,请使用/.../

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

Hmm yeah... what you're doing is absolutely wrong.嗯是的...你在做什么是完全错误的。 When you say str.split("\\r\\n|\\r|\\n") it will try to find the exact string "\\r\\n|\\r|\\n" .当您说str.split("\\r\\n|\\r|\\n")它会尝试找到确切的字符串"\\r\\n|\\r|\\n" That's where you're wrong.那就是你错了。 There's no such occurance in the whole string.整个字符串中没有这种情况。 What you really want is what David Hedlund suggested:你真正想要的是 David Hedlund 的建议:

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

The reason is that the split method doesn't convert strings into regular expressions in JavaScript.原因是 split 方法不会将字符串转换为 JavaScript 中的正则表达式。 If you want to use a regexp, use a regexp.如果要使用正则表达式,请使用正则表达式。

I made a performance test comparing split with regex, with a string and doing it with a for loop.我做了一个性能测试,将 split 与正则表达式、字符串和 for 循环进行比较。

It seems that the for loop is the fastest.似乎for循环是最快的。

NOTE: this code 'as is' is not useful for windows nor macos endline, but should be ok to compare performance.注意:此代码“按原样”对 windows 或 macos 端线没有用,但应该可以比较性能。

Split with string:用字符串分割:

split('\n').length;

Split with regex:用正则表达式拆分:

split(/\n/).length;

Split using for:拆分用于:

var length = 0;
for(var i = 0; i < sixteen.length; ++i)
  if(sixteen[i] == s)
    length++;

http://jsperf.com/counting-newlines/2 http://jsperf.com/counting-newlines/2

There are three options:共有三个选项:

Using jQuery (download from jQuery website ) - jquery.com使用 jQuery(从jQuery 网站下载) - jquery.com

var lines = $("#ptest").val().split("\n");
return lines.length;

Using Regex使用正则表达式

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

Or, a recreation of a for each loop或者,为每个循环重新创建一个

var length = 0;
for(var i = 0; i < str.length; ++i){
    if(str[i] == '\n') {
        length++;
    }
}
return length;

Better solution, as str.split("\\n") function creates new array of strings split by "\\n" which is heavier than str.match(/\\n\\g).更好的解决方案,因为 str.split("\\n") 函数创建了由 "\\n" 分割的新字符串数组,这比 str.match(/\\n\\g) 重。 str.match(/\\n\\g) creates array of matching elements only. str.match(/\\n\\g) 仅创建匹配元素的数组。 Which is "\\n" in our case.在我们的例子中是“\\n”。

var totalLines = (str.match(/\n/g) || '').length + 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>

thats works in my case这在我的情况下有效

Another solution for this problem using the spread operator and no regular expressions would be:使用扩展运算符且不使用正则表达式来解决此问题的另一个解决方案是:

const lines = [...csv].reduce((a, c) => a + (c === '\n' ? 1 : 0), 0)

 const csv = ` demo_budget_2021_v4_wk_9,test,Civil,Spares,test,false,12,2021,100 demo_budget_2021_v4_wk_9,test,Civil,Spares,test,false,11,2021,100 demo_budget_2021_v4_wk_9,test,Civil,Spares,test,false,10,2021,100 demo_budget_2021_v4_wk_9,test,Civil,Spares,test,false,9,2021,100 ` const lines = [...csv].reduce((a, c) => a + (c === '\\n' ? 1 : 0), 0) console.log(lines);

Here is the working sample fiddle这是工作示例小提琴

Just remove additional \\r\\n and "|"只需删除额外的 \\r\\n 和 "|" from your reg ex.来自您的 reg ex。

I was testing out the speed of the functions, and I found consistently that this solution that I had written was much faster than match ing.我正在测试函数的速度,我一直发现我编写的这个解决方案比match快得多。 We check the new length of the string as compared to the previous length.我们检查字符串的新长度与之前的长度相比。

const lines = str.length - str.replace(/\n/g, "").length+1;

 let str = `Line1 Line2 Line3`; console.time("LinesTimer") console.log("Lines: ",str.length - str.replace(/\\n/g, "").length+1); console.timeEnd("LinesTimer")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM