Roma Kap
Roma Kap

Reputation: 636

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?

Upvotes: 1

Views: 950

Answers (1)

Pranav C Balan
Pranav C Balan

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?


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

Upvotes: 1

Related Questions