如何在javascript中计算字符串的行数 [英] How to count the number of lines of a string in javascript

查看:46
本文介绍了如何在javascript中计算字符串的行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想计算一个字符串中的行数

I want to count the number of lines in a string

我尝试使用这个 stackoverflow 答案:

i tried to use this stackoverflow answer :

lines = str.split("
|
|
"); 
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

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

and for some reason i got lines='1'.

知道如何让它工作吗?

推荐答案

使用正则表达式可以将行数计算为

Using a regular expression you can count the number of lines as

 str.split(/
|
|
/).length

或者,您可以尝试如下拆分方法.

Alternately you can try split method as below.

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

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

这篇关于如何在javascript中计算字符串的行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆