正则表达式从字符串中删除某些类的html标记 [英] Regex to remove html tags with certain class from string

查看:98
本文介绍了正则表达式从字符串中删除某些类的html标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要删除所有 a 标记,这些标记具有字符串中的某个类并将它们存储在另一个字符串中。例如:

I need to remove all a tags which have a certain class from a string and store them in another string. For example:

var str = 'this is a string <a href="#" class="link">link</a>';

我想用 class =link剥离标签并保存在 str2 中。

推荐答案

var re = /(<a(?: \w+="[^"]+")* class="link"(?: \w+="[^"]+")*>([^<]*)<\/a>)/g;
var str = 'this is a string <a href="#" class="link">link</a> <a class="link">link2</a>';

var links = [] # array of <a> tags
for (var i in str.match(re)) {
    links.push(str.match(re)[i])
}

var embedded_strings = [] # array of strings inside <a> tags
for (var i in links) {
    embedded_strings.push(links[i].replace(re, "$2"))
}

结果:

links = ['<a href="#" class="link">link</a>', '<a class="link">link2</a>']
embedded_strings = ['link', 'link2']

这个答案假定 =周围没有空格并且您将仅使用双引号。

This answer assumes that there will be no whitespace around = and that you will use double quotes exclusively.

这篇关于正则表达式从字符串中删除某些类的html标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆