标签搜索

目 录CONTENT

文章目录

JavaScript实现正则去除指定标签只保留内容的方法

沙漠渔
2022-07-12 11:27:58 / 0 评论 / 0 点赞 / 870 阅读 / 635 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2022-07-12,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

由于目前有个想法(你们可以猜测一下是要做啥),需要获取到页面之后将获取到的DOM元素中的指定标签(比如a标签)删除掉,但是保留标签里的内容,于是首先想到的是正则表达式来处理

问题描述

例如有下HTML代码,想去掉里面的a标签、span标签,只留下内容 https://www.sammery.com 我们需要怎么做呢?

<a href="https://www.sammery.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;">https://www.sammery.com</span></a>

解决思路

首先我们需要使用正则表达式找出a标签和span标签

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

然后使用js执行替换操作

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

如果想替换所有,可以参考 关于JavaScript .replaceAll() is not a function type error问题 - 沙漠渔溏

测试代码如下:

<!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正则删除指定标签并保留内容</title>
</head>
<body>
<a href="https://www.sammery.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;">https://www.sammery.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>
0
广告 广告

评论区