如何计算javascript中字符串的行数 [英] How to count the number of lines of a string in javascript
本文介绍了如何计算javascript中字符串的行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想计算一个字符串中的行数
I want to count the number of lines in a string
我试图使用这个stackoverflow答案:
i tried to use this stackoverflow answer :
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
由于某种原因我得到了行='1'。
and for some reason i got 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);
工作解决方案: http://jsfiddle.net/C8CaX/
这篇关于如何计算javascript中字符串的行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文