i have some text in javascript like this:
This is my text<br>This is my second line of text
and i want to have a function that will return
This is my text
so basically find the last
<br>
in the text and give me everything before it.
If your text is really that simple, you could do a .split()
on the <br>
var str = "This is my text<br>This is my second line of text"
var result = str.split('<br>')[0];
If it is more complex, it may be worthwhile to use the browser's built in HTML parser, so you can operate on them like DOM nodes.
In this case, it could look like this:
var div, result, str = "This is my text<br>This is my second line of text";
(div = document.createElement('div')).innerHTML = str;
var result = div.firstChild.data;
...or perhaps a little simpler with jQuery:
var str = "This is my text<br>This is my second line of text"
var result = $('<div>',{html:str}).contents().first().text();
If you're sure that the br will not be an XHTML br, Maxym's answer works fine. Otherwise, a regex should do it:
var result = text.match(/([\s\S]+)<br\s*\/?>[\s\S]*$/i)[1];
精彩评论