开发者

Get last line of HTML with Javascript

How can I get the last line of HTML text with Javascript?

For example, a HTML request returns thi开发者_高级运维s response:

<span>blah blah blah
ha ha ha ha
tatatatata

How would I get the last line "tatatatata"?


var html = document.getElementById('some_element').innerHTML.split(/\r?\n/);
alert(html[html.length - 1]);

Split by /\r?\n/ to break the HTML into lines, then grab the last element of the array.

Note: since this is HTML, you may want to split by /<br(?: \/)?>/ or /<br>/, depending on the situation.


$('#your_span').html().split(/\r?\n/).pop()

https://www.w3schools.com/jsref/jsref_pop.asp


You can read in all the HTML markup, do a split() on line breaks, and get the last item in the array.


You can use javascript's lastIndexOf, like this:

var your_html = 'blah<br />ha ha<br />tata';
var newline_mark = '<br />';
var last_br_position = your_html.lastIndexOf(newline_mark);
var last_line;
if (last_br_position == -1)
    last_line = your_html;
else
    last_line = your_html.substr(last_br_position + newline_mark.length);


Assuming that there is only one <span> on the page....

var lines = document.getElementsByTagName("span")[0].innerText.split("\n");
alert(lines[lines.length-1]);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜