首页 > 编程 > JavaScript > 正文

JavaScript实现正则去除a标签并保留内容的方法【测试可用】

2019-11-19 13:27:57
字体:
来源:转载
供稿:网友

本文实例讲述了JavaScript实现正则去除a标签并保留内容的方法。分享给大家供大家参考,具体如下:

一、问题:

有如下HTML代码,要求用正则去除a标签,只留下内容 //www.VeVB.COm

复制代码 代码如下:
<a href="//www.VeVB.COm/" 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.VeVB.COm</span></a>

二、解决方法:

这里使用可删除a标签与span标签的正则语句,如下:

(<//?a.*?>)|(<//?span.*?>)

具体js正则语句:

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.VeVB.COm/" 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.VeVB.COm</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.VeVB.COm/code/HtmlJsRun,测试结果如下:

PS:这里再为大家提供2款非常方便的正则表达式工具供大家参考使用:

JavaScript正则表达式在线测试工具:
http://tools.VeVB.COm/regex/javascript

正则表达式在线生成工具:
http://tools.VeVB.COm/regex/create_reg

更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《JavaScript正则表达式技巧大全》、《JavaScript替换操作技巧总结》、《JavaScript查找算法技巧总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript遍历算法与技巧总结》、《JavaScript中json操作技巧总结》、《JavaScript错误与调试技巧总结》及《JavaScript数学运算用法总结

希望本文所述对大家JavaScript程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表