roi
roi

Reputation: 59

change surrounding tags for a given text by RegExp

I try to create function that find text in my htmlString (it minify) and then change the tag that wrap the text to h2

 var htmlString = `
<h1>title</h1><p>Lorem ipsum dolor quas!</p><p>Lorem ipsum dolor</p><p>hi</p><p>hi 123</p><div>hi</div><span>Lorem ipsum dolor, sit.</span>
`
const changeTagByText = (html) => {
let text = "hi"

// replace the tags

return html
}

console.log(changeTagByText(html)) 

output excepted:

<h1>title</h1><p>Lorem ipsum dolor quas!</p><p>Lorem ipsum dolor</p><h2>hi</h2><p>hi 123</p><h2>hi</h2><span>Lorem ipsum dolor, sit.</span>

Upvotes: 2

Views: 73

Answers (1)

SelVazi
SelVazi

Reputation: 16083

var htmlString = `<h1>title</h1><p>Lorem ipsum dolor quas!</p><p>Lorem ipsum dolor</p><p>hi</p><p>hi 123</p><div>hi</div><span>hi</span><span>Lorem ipsum dolor, sit.</span>
`
const changeTagByText = (html, word) => {
  var re = new RegExp('(<[a-zA-Z]+>)'+ word +'(</[a-zA-Z]+>)', 'g')
  return html.replace(re, '<h1>'+ word +'</h1>');
}
console.log(changeTagByText(htmlString, 'hi'))

You can do it more dynamically by expand changeTagByText to take two params one for the html and the other one for the text you want to replace.

RegExp help to create dynamic regex pattern.

Upvotes: 1

Related Questions