0

I wanted to make a syntax highlighter that highlights symbols. Look at the example:

function hello(){
  return "hello";
}

I want to highlight all the symbols:

{([</!&|\>])};.,:=+*-@$~_^?%'"

And I made a little one that highlighted strings. When I wanted to make one that highlights symbols I got confused. Now I want to know What topics should I learn to make it? Any example, github repo, tutorial, topic or ...? EDIT: I found the way to do that but I still have problem. My code is the following:

function syntaxue(){
  var codes = document.getElementsByClassName("syntaxue");
  for (var i=0; i < codes.length; i++){
    var data = codes[i].innerHTML;
    data = data.replace(/([^\w\s])/g, '<span class="sym">$1</span>');
    data = data.replace(/([\d])/g, '<span class="num">$1</span>');
    codes[i].innerHTML = data;
  }
}

When I want to highlight strings, the code becomes sth else.(Sorry I'm not English) And I was testing HTML markup I saw this:

&lt;html&gt;

Instead of this:

<html>

And the &; symbols were highlighted not their results. Can anyone help me?

Front Cutted
  • 9
  • 1
  • 3
  • In order to tell what's missing, you should tell what you have. Show how you _made a little one that highlighted strings_ and say how it doesn't apply to _symbols_. – Armali Oct 29 '21 at 17:27
  • Generally speaking, if you want to affect *text*, then you shouldn't be modifying *HTML*. Instead, you should be looping through all text nodes, finding the stuff you want, splitting the text node at that position and wrap the match with your desired HTML. You have many *powerful* DOM functions available to you, they should be used. [Not regex!](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454) – Niet the Dark Absol Oct 29 '21 at 19:21

0 Answers0