Regex for removing tag in javascript

1030 views javascript
-2

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?

answered question

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

3 Answers

13

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.

posted this
2

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)

posted this
2

Please try with the following regex :

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

posted this

Have an answer?

JD

Please login first before posting an answer.