开发者

avoiding newline from split()?

I have a list in a string, as below (from a <textarea> element with id=list):

q1

开发者_运维问答q2
q3


q4 

JavaScript:

var TA = document.getElementById("list").value; 
lines = TA.split("\r\n");

I want lines variable to have the values q1,q2,q3,q4, but the result is q1,,q2,q3,,,q4 (note the empty items)

I want to avoid the blank strings in the result array - how can I do that?


Try something like this, which should also take care of other formats of new lines (for example, only \n):

var lines = TA.split(/[\r\n]+/);

Or, to remove blank lines and spaces before/after your tokens (this one will only match the \r\n format, but you can use [\r\n] instead):

var lines = TA.split(/\s*\r\n\s*/);

Alternatively, you can match the lines instead of splitting the newlines:

var lines = TA.match(/.+/g);

. doesn't match new lines, so .+ is really matching a whole line, and skips empty lines. This will also skip empty tokens at the beginning or end of the array (as in \n\n a \n b), while split still creates empty elements.


You could remove empty elements from the array after splitting it. See

Remove empty elements from an array in Javascript


Replace multiple \r\n by one before splitting

TA.replace(/(\r\n)+/g, "\r\n").split("\r\n")


Use var lines = TA.split(/[\r\n]{1,}/g);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜