-2

Can somebody help me on this:

console.log('<span class="tooltip">aaaa</span><b>ok</b> <span class="tooltip">bbbb</span>'.replace('/<span .*?class="(.*?tooltip.*?)">(.*?)<\/span>/\g', ''))

I would like to remove span tags with class name .tooltip and so this to print in console "ok"

Also i would like not to trim the string so if any hidden char is present like \n should not be removed.

itsme
  • 48,972
  • 96
  • 224
  • 345

2 Answers2

2

You can do this:

const data = '<span class="tooltip">aaaa</span><b>ok</b> <span class="tooltip">bbbb</span>'
const removeTags = data => data.replace(/\s*<span.*?class="tooltip".*?>(.*?)\s*<\/span>\s*/g, '')

console.log(removeTags(data))

This will also match multiline:

const data = `<span class="tooltip">aaaa

</span><b>ok</b> <span class="tooltip">bbbb</span>`
const removeTags = data => data.replace(/(?:\s|\n)*<span(?:.|\n)*?class="tooltip"(?:.|\n)*?>(?:[^])*?(?:\s|\n)*<\/span>(?:\s|\n)*/g, '')
console.log(removeTags(data))
Maciej Kozieja
  • 1,812
  • 1
  • 13
  • 32
0

You can use .getElementsByClassName() to find them and .remove() to remove them:

var input = '<span class="tooltip">aaaa</span><b>ok</b> <span class="tooltip">bbbb</span>';
var dom = document.createElement("div");
var toRemove;

dom.innerHTML = input;
toRemove = dom.getElementsByClassName("tooltip");
while (toRemove.length > 0) {
  toRemove[0].remove();
}
console.log(dom.innerHTML);

For more complex selections you can use, for instance, .querySelectorAll().

This approach admittedly does not use regular expressions but it has the advantage of being easier to maintain and more robust (HTML is not a regular language thus cannot be reliably parsed with regular expressions).

Community
  • 1
  • 1
Álvaro González
  • 142,137
  • 41
  • 261
  • 360