0

I have a small piece of text: "some text" some more text "even more text"

What I wanna do is to wrap everything between apostrophes in a span container just like hilight.js does. I can't really find a way to make it working.

Could somebody please explain me what would be the ideal way to do this?

var body = document.querySelector('body');

var code = body.innerHTML;
var code = code.replace(/"(.*?)"/g,"<span>---</span>");
body.innerHTML = code;
span {
  color: red;
}
<body>
<p>Corrent result:</p>
"some text" some more text "even more text"
<p>The result would be:</p>
<p><span>some text</span> some more text <span>even more text</span></p>
</body>
Shape
  • 410
  • 1
  • 3
  • 21
  • Replace `---` with `$1`. – Ry- Jul 10 '19 at 20:20
  • Can you explain me how does it work? – Shape Jul 10 '19 at 20:20
  • https://stackoverflow.com/questions/1234712/javascript-replace-with-reference-to-matched-group – Ry- Jul 10 '19 at 20:21
  • I'm not sure if I would want to do that... The browser would recognize `$1` as a variable – Shape Jul 10 '19 at 20:22
  • Not sure what you mean by that. Also, make sure you’re doing that on something that’s originally HTML, though, and that doesn’t have attributes. It’s easy to make a script injection vulnerability or mangle real-world HTML. So: are you doing this on HTML, or on text? – Ry- Jul 10 '19 at 20:22
  • So I would just need to replace the content of the string itself? – Shape Jul 10 '19 at 20:24
  • @Rt- It's HTML stored in a variable, after wrapping the text I write it back onto the page. – Shape Jul 10 '19 at 20:25
  • And it never has any attributes in it, like ``? – Ry- Jul 10 '19 at 20:26
  • The only attribute I use is the class attribute so I can style the wrapper element. – Shape Jul 10 '19 at 20:27
  • Great, just wanted to make sure it was safe to use :D – Ry- Jul 10 '19 at 20:33

1 Answers1

1

You're quite close. You can use $n syntax in your replace string which will correspond to the n'th capture group.

let x = '"yo" bro "more"';
let y = x.replace(/"(.*?)"/g, '<span>$1</span>');
console.log(y);

mdn

junvar
  • 11,151
  • 2
  • 30
  • 46