// 示例代码:去除HTML标签
function stripHtmlTags(html) {
// 创建一个临时的DOM节点
const tempDiv = document.createElement("div");
// 将HTML字符串设置为该节点的innerHTML
tempDiv.innerHTML = html;
// 返回文本内容,即去除了所有HTML标签的内容
return tempDiv.textContent || tempDiv.innerText || "";
}
// 示例用法
const htmlString = "<p>这是一个<strong>测试</strong>段落。</p>";
const plainText = stripHtmlTags(htmlString);
console.log(plainText); // 输出: 这是一个测试段落。
// 解释说明:
// 1. 创建一个临时的div元素,利用其innerHTML属性解析HTML字符串。
// 2. 通过访问textContent或innerText属性获取纯文本内容,从而去除所有HTML标签。
// 3. textContent是标准属性,支持大多数现代浏览器;innerText是IE特有的属性,用于兼容性处理。
上一篇:json转html
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站