我有一些像这样的 javascript 文本:
This is my text<br>This is my second line of text
我想有一个函数可以返回
This is my text
所以基本上找到最后一个
<br>
在文本中并在它之前给我所有内容。
最佳答案
如果您的文本真的那么简单,您可以做 .split()
在 <br>
上
var str = "This is my text<br>This is my second line of text"
var result = str.split('<br>')[0];
如果比较复杂,可能值得使用浏览器内置的 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;
...或者使用 jQuery 可能更简单一些:
var str = "This is my text<br>This is my second line of text"
var result = $('<div>',{html:str}).contents().first().text();
关于javascript - 如何在javascript中解析字符串并捕获最后一个<br>之前的所有文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4985035/