Javascript 循环遍历字符串中的html标记,并将内部文本添加到数组中
我有一些HTML内容保存为字符串 我想循环遍历该字符串中的每个标题标记,并获取其内部文本Javascript 循环遍历字符串中的html标记,并将内部文本添加到数组中,javascript,regex,Javascript,Regex,我有一些HTML内容保存为字符串 我想循环遍历该字符串中的每个标题标记,并获取其内部文本 let str=`topic 1topic 1的描述topic 2topic 2的描述`; 常量innerHTMLarr=str.match(/(.*)/g).map(x=>x); console.log(innerHTMLarr)在映射()中尝试/g替换所有出现的和,如下所示: let str=`topic 1topic 1的描述topic 2topic 2的描述`; 常量innerHTMLarr=s
let str=`topic 1topic 1的描述topic 2topic 2的描述`;
常量innerHTMLarr=str.match(/(.*)/g).map(x=>x);
console.log(innerHTMLarr)
在映射()中尝试/g
替换所有出现的
和
,如下所示:
let str=`topic 1topic 1的描述topic 2topic 2的描述`;
常量innerHTMLarr=str.match(/(.*)/g).map(val=>{
return val.replace(//g',);
});
console.log(innerHTMLarr)
从以下位置应用解决方案:
let str=`topic 1topic 1的描述topic 2topic 2的描述`;
设regexpr=/(.*)/g;
让match=regexpr.exec(str);
while(匹配!==null){
console.log(匹配[1]);
match=regexpr.exec(str);
}
您可以在循环中使用,直到没有匹配为止
编辑:简化代码
let模式=/(.*)/g;
设str=`topic 1topic 1的描述topic 2topic 2的描述`;
让我们比赛;
while(match=pattern.exec(str))
console.log(匹配[1])代码>使用jQuery,可以通过以下方式执行:
let str='topic 1topic 1的描述topic 2topic 2的描述';
html=$.parseHTML(str);
InnerHtmlAr=[],k=0;
$.each(html、函数(i、el){
if(el.nodeName.startsWith('H'))
innerHTMLarr[k++]=el.innerHTML;
});
console.log(innerHTMLarr)代码>
请参考此可能的副本,另请参见>结果未定义谢谢。你能告诉我返回值是多少吗?替换(//g',);正在做什么?它将替换为空string@totalnoob,我在答案中添加了一点解释…希望能澄清您的问题…谢谢。$(“H1”)。每个(函数(){/*一些代码*/})代码>?