-3

I have this tag:

const tag = '<symbol xmlns="http://www.w3.org/2000/svg" viewBox="0 0 28.3 28.3" id="logo-square-empty"><path fill="none" d="M-.7-.9h30v30h-30z" /><path d="M0 28.3h28.3V0H0v28.3zM3.5 3.5h21.3v21.3H3.5V3.5z" /></symbol>'

I want to remove the <symbol> and </symbol> tags, and get this result:

<path fill="none" d="M-.7-.9h30v30h-30z" /><path d="M0 28.3h28.3V0H0v28.3zM3.5 3.5h21.3v21.3H3.5V3.5z" />

So I wrote this regex:

/</?symbol[^>]*>/;

Which can be tested here: https://regexr.com/42fan

And I should be able to do:

const regex = /</?symbol[^>]*>/;
const replacedString = tag.replace(regex, '');

But I get Parsing error: Unexpected token ^. How should I write it to avoid this parsing error?

3 Answers3

1

Instead of parsing HTML we can manipulate with tag as HTML:

const tag = '<symbol xmlns="http://www.w3.org/2000/svg" viewBox="0 0 28.3 28.3" id="logo-square-empty"><path fill="none" d="M-.7-.9h30v30h-30z" /><path d="M0 28.3h28.3V0H0v28.3zM3.5 3.5h21.3v21.3H3.5V3.5z" /></symbol>'

var div = document.createElement('DIV')
div.innerHTML = tag
result = div.firstElementChild.innerHTML.toString()
console.log(result)
qiAlex
  • 4,290
  • 2
  • 19
  • 35
0

You have not escaped the / in your regular expression. You won't have errors with this:

/<\/?symbol[^>]*>/

That said, it won't work for your task and is still a bad idea to parse your HTML with a regex. And you may prefer to work directly with your DOM, using a getElementByXXX javascript method.

Ulysse BN
  • 10,116
  • 7
  • 54
  • 82
0

Please try with the following regex :

const regex = /<\/?symbol[^>]*>/;
const replacedString = tag.replace(regex, '');