-1

I'm making a syntax highlight, with live code editor.here the example image

here de example of string code:

// before.

var x = 'person + arthur' + "family + all";

// after.

var x = 'person + arthur' <span style="color:red;">+</span> "family + all";

Im using:

var x = string.replace(/\+/g,'<span style="color: red;">+</span>'); // but this replace all.

I need replace only outside of single quotes and double quotes.

Im using a Get .innerText, for avoid conflicts in the regex.

genife
  • 24
  • 6

1 Answers1

1

Try this:

str = `var x = 'person + arthur' + "family + all";`;

str = str.replace(/(['"])[^'"]*\1|[-*\/%+]/g, x => (x.length == 1) ? '<span style="color:red;">' + x + '</span>' : x);


console.log(str)

Try it live on Regex101.

Basically the regex matches all strings, leaving the characters [-*\/%+] which are not inside quotes free to match.

Washington Guedes
  • 4,254
  • 3
  • 30
  • 56