简体   繁体   English

javascript 替换标记正则表达式不依赖 html 属性

[英]javascript replace tag-regex undepend html-attributes

i'm trying whole the time to replace such strings:我一直在尝试替换这些字符串:

<title id="hello">my title </title>
<title >my title </title>
<title id="hello" class="blue">my title </title>

i need regex, which replace text between title-tags, undepend attributes.我需要正则表达式,它替换标题标签之间的文本,不依赖属性。 sadly i get only second example with this regex:遗憾的是,我只得到了这个正则表达式的第二个例子:

str.replace(/<\/?title>/g,'')

Has anybody ideas?有任何想法吗?

It's always better to avoid using regex for parsing HTML.最好避免使用正则表达式来解析 HTML。

RegEx match open tags except XHTML self-contained tags RegEx 匹配除 XHTML 自包含标签之外的开放标签

Using regular expressions to parse HTML: why not? 使用正则表达式解析 HTML:为什么不呢?


Instead, generate a temporary DOM element with the content and applying all the change finally get the HTML content. 相反,使用内容生成临时 DOM 元素并应用所有更改最终获得 HTML 内容。

 var html = `<title id="hello">my title </title> <title >my title </title> <title id="hello" class="blue">my title </title>`; // generate a temporary div elementt var temp = document.createElement('div'); // set its html content as the string temp.innerHTML = html; //do the rest here // get all title tags Array.from(temp.getElementsByTagName('title')) // iterate over the title tag and do the necessary chenges .forEach(function(ele) { ele.innerHTML = 'new content' }) // get back the updated html content from dom element console.log(temp.innerHTML);


Fore NodeJS refer : HTML-parser on Node.js前 NodeJS 参考: Node.js 上的 HTML-parser

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM