简体   繁体   中英

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.

RegEx match open tags except XHTML self-contained tags

Using regular expressions to parse HTML: why not?


Instead, generate a temporary DOM element with the content and applying all the change finally get the HTML content.

 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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