本文介绍如何使用JavaScript正则表达式去除HTML中的a标签并保留其内部文本内容。通过示例代码演示了匹配a和span标签的正则写法,并提供了在线测试工具及正则表达式生成器的链接,帮助开发者快速实现字符串清洗。
本文详细介绍在JavaScript中利用正则表达式移除HTML链接标签同时保留文本内容的实现方案,供读者参考应用。
问题描述
一、问题描述:
有如下HTML代码,要求用正则去除a标签,只留下内容 //www.jb51.net
代码示例如下:
<a href="//www.jb51.net/" style="box-sizing: border-box; color: rgb(51, 51, 51); text-decoration: none; transition: all 0.5s cubic-bezier(0.175, 0.885, 0.32, 1); -webkit-transition: all 0.5s cubic-bezier(0.175, 0.885, 0.32, 1); max-width: 100%; transparent;"><span data-wiz-span="data-wiz-span" style="box-sizing: border-box; max-width: 100%; font-size: 14pt;">//www.jb51.net</span></a>
解决方案
二、解决方案:
此处采用能够匹配并删除a标签及span标签的正则表达式,具体逻辑如下:
正则表达式核心逻辑
(<\/?a.*?>)|(<\/?span.*?>)
核心JavaScript正则表达式语句:
代码实现
str.replace(/(<\/?a.*?>)|(<\/?span.*?>)/g, '');
完整的测试代码示例如下:
完整测试代码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>js正则删除a标签并保留内容</title>
</head>
<body>
<a href="//www.jb51.net/" style="box-sizing: border-box; color: rgb(51, 51, 51); text-decoration: none; transition: all 0.5s cubic-bezier(0.175, 0.885, 0.32, 1); -webkit-transition: all 0.5s cubic-bezier(0.175, 0.885, 0.32, 1); max-width: 100%; transparent;"><span data-wiz-span="data-wiz-span" style="box-sizing: border-box; max-width: 100%; font-size: 14pt;">//www.jb51.net</span></a>
<script>
var str=document.getElementsByTagName('a')[0].outerHTML;
console.log("正则删除之前:"+str);
str=str.replace(/(<\/?a.*?>)|(<\/?span.*?>)/g, '');
console.log("正则删除之后:"+str);
</script>
</body>
</html>
在线测试与工具推荐
可通过在线HTML/CSS/JavaScript代码运行工具进行验证:http://tools.jb51.net/code/HtmlJsRun,测试结果如下:

补充推荐两款实用的正则表达式辅助工具:
JavaScript正则表达式在线测试工具: http://tools.jb51.net/regex/javascript
正则表达式在线生成工具: http://tools.jb51.net/regex/create_reg
如需深入了解JavaScript相关知识,建议参考本站系列文章:《JavaScript正则表达式技巧大全》、《JavaScript替换操作技巧总结》、《JavaScript查找算法技巧总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript遍历算法与技巧总结》、《JavaScript中json操作技巧总结》、《JavaScript错误与调试技巧总结》及《JavaScript数学运算用法总结》。
希望本文提供的JavaScript编程技巧能对大家有所帮助。