全国统一服务热线:400-633-9193

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

    网络     2018-09-03    1396

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

一、问题:

有如下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标签的正则语句,如下:

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

具体js正则语句:

1
str.replace(/(<\/?a.*?>)|(<\/?span.*?>)/g, '');

完整测试代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!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,测试结果如下:


  分享到:  
5.8294s