如何解析javascript中的字符串并捕获最后一个<br>之前的所有文本

leo*_*ora 1 javascript string jquery

我在 javascript 中有一些这样的文本:

This is my text<br>This is my second line of text
Run Code Online (Sandbox Code Playgroud)

我想要一个可以返回的函数

This is my text
Run Code Online (Sandbox Code Playgroud)

所以基本上找到最后一个

<br>
Run Code Online (Sandbox Code Playgroud)

在文本中,并在它之前给我一切。

use*_*716 5

如果你的文字真的那么简单,你可以.split()<br>

var str = "This is my text<br>This is my second line of text"
var result = str.split('<br>')[0];
Run Code Online (Sandbox Code Playgroud)

如果比较复杂,可能值得使用浏览器内置的 HTML 解析器,这样您就可以像操作 DOM 节点一样操作它们。

在这种情况下,它可能如下所示:

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;
Run Code Online (Sandbox Code Playgroud)

...或者也许使用 jQuery 更简单一点:

var str = "This is my text<br>This is my second line of text"
var result = $('<div>',{html:str}).contents().first().text();
Run Code Online (Sandbox Code Playgroud)