Reputation: 636
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?
Upvotes: 1
Views: 950
Reputation: 115222
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?
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
Upvotes: 1