嗨,我试图从显示错误的特定字符串中删除所有html标记.
这是我的字符串:
<p>Hi there</p> ~ wifi free <p>this is test</p> ~ breakfast free <p>This is another test</p>
Run Code Online (Sandbox Code Playgroud)
我的jQuery代码在这里:
var item = <p>Hi there</p> ~ wifi free <p>this is test</p> ~ breakfast free <p>This is another test</p>;
item = item.replace(/~/g, '');
item = item.replace(/<p>/g, '');
item = item.replace('</p>'/g, '');
var splitArray = item.split('<br />');
var l = splitArray.length;
for (var i = 0; i < l; i++) {
out = out + "<li><span class='sp_icon sp_star_icon'></span> "
+ splitArray[i].trim() + "</li>";
}
console.log(item);
Run Code Online (Sandbox Code Playgroud)
ple*_*xus 20
你可以用正则表达式删除所有的html标签:/<(.|\n)*?>/g
这里详细描述:http://www.pagecolumn.com/tool/all_about_html_tags.htm
在你的JS代码中,它看起来像这样:
item = item.replace(/<(.|\n)*?>/g, '');
Run Code Online (Sandbox Code Playgroud)
不要自己做,让 DOM 为你做。
例如(使用 jQuery)
jQuery("<p>Hi there</p>...").text();
// => "Hi there..."
Run Code Online (Sandbox Code Playgroud)
例如(没有 jQuery)
var d = document.createElement('div');
d.innerHTML = "<p>Hi there</p>...";
(d.textContent || d.innerText); // => "Hi there..."
Run Code Online (Sandbox Code Playgroud)
使用 vanilla JS,您可以这样做
var item = '<p>Hi there</p> ~ wifi free <p>this is test</p> ~ breakfast free <p>This is another test</p>';
function getText(html) {
var tmp = document.createElement('div');
tmp.innerHTML = html;
return tmp.textContent || tmp.innerText;
}
console.log(getText(item));Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16928 次 |
| 最近记录: |