龙空技术网

js提取html富文本字符串某个标签的所有属性

你的Maya 49

前言:

现时大家对“js获取标签的属性内容”大概比较看重,姐妹们都想要知道一些“js获取标签的属性内容”的相关知识。那么小编在网络上收集了一些对于“js获取标签的属性内容””的相关内容,希望各位老铁们能喜欢,兄弟们快快来了解一下吧!

在HTML中,标签可以包含各种属性,用于定义标签的特性和行为。例如,img标签可以有src属性来指定要显示的图像的URL,a标签可以有href属性来指定链接的目标地址。通过获取标签的属性值,我们可以获取到这些额外的信息,然后根据需要进行处理。

定义方法

/** * 提取富文本字符串某个标签的所有属性 * @param {String} str 要提取的html富文本 * @param {Object} tagName 要提取的标签名称 * @param {Object} attrName 要提取的属性名称 * @returns {Array} list 属性列表 */function getStrTagAttribute(str,tagName,attrName){	let attributeList = []	const re = new RegExp(`<${tagName} [^>]*${attrName}=['"]([^'"]+)[^>]*>`,'g')	str.replace(re, (match, capture) => {	  attributeList.push(capture);	});	return attributeList;}

使用方法

// 定义html富文本const htmlStr = `<p style="text-indent: 2em;">	<span style="font-size: 18px;">3月12日,郴州市科技局党组书记、局长肖亮带队到市林科所开展“四下基层”工作面存在的困难。</span></p><p style="text-align: center; text-indent: 0em;">	<img src="iurl://resources/image/2024/03/14/525293007499333.jpg?type=resource&id=525293007499333&st=Local&sid=1630092239507464193" class="art-body-img" /></p><p style="text-indent: 0em; text-align: center;">	<img src="iurl://resources/image/2024/03/14/525293197901893.jpg?type=resource&id=525293197901893&st=Local&sid=1630092239507464193" class="art-body-img" /></p><p style="text-indent: 0em; text-align: center;">	<img src="iurl://resources/image/2024/03/14/525293307740229.jpg?type=resource&id=525293307740229&st=Local&sid=1630092239507464193" class="art-body-img" /></p><p style="text-indent: 0em; text-align: center;">调研活动现场图</p>`// 调用方法const list = getStrTagAttribute(htmlStr,'img','src')// 输出结果console.log('list----->',list)// list-----> [//     "iurl://resources/image/2024/03/14/525293007499333.jpg?type=resource&id=525293007499333&st=Local&sid=1630092239507464193",//     "iurl://resources/image/2024/03/14/525293197901893.jpg?type=resource&id=525293197901893&st=Local&sid=1630092239507464193",//     "iurl://resources/image/2024/03/14/525293307740229.jpg?type=resource&id=525293307740229&st=Local&sid=1630092239507464193"// ]

标签: #js获取标签的属性内容 #js获取标签的属性内容是什么 #js获取标签的属性内容是什么类型 #js获取标签的属性内容是什么类型的 #js获取标签的属性内容是什么类型的命令