0

I have a user input field in html, and I want to grab text that is tagged by characters, and then replace the text inside of the tags with a html span tags. Example of text in an html element:

@"this is a text tag" inside of an html element, the tag is anything starting with an '@' character followed by a quotation character (") and closed by a quotation character. So this is @"also a tag".

I want to convert  @"this is a text tag" to <span>this is a text tag</span> 
and @"also a tag" become <span>also a tag</span>

Here's the code I started with but I'm a bit lost:

        let text = htmlElement.textContent;
        let regex = /@"(.*?)"/g;
        let match = text.replace(regex, `<span>/*the text in the tag here*/</span>`);
        console.log(match);

Any help is appreciated!

Ron I
  • 4,090
  • 8
  • 33
  • 64

1 Answers1

3

Your captured group will contain the text inside the "s, so all you need to do is put the captured group inside the <span></span> with $1:

const replacedText = htmlElement.textContent.replace(
  /@"([^"]+)"/g,
  `<span>$1</span>`
);
console.log(replacedText);
<div id="htmlElement">I want to convert  @"this is a text tag" !
and @"also a tag" become</div>

Note that you can use a negative character set ([^"]+) instead of .*? to make the regular expression a bit more efficient.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320