I'm trying to make a syntax highlighting system for Java code using JavaScript. So far, I've figured out how to color individual words, but when I try to color multiple words, it replaces the new keyword with the original one. Here is a picture example:
The "main" in the beginning is supposed to say public. How do I do JavaScript RegExp for multiple keywords and still retain my text? Code: http://jsfiddle.net/vtnd02e7/
<h3>Original Text</h3>
<textarea id="origtext">
</textarea>
<button onclick="colorize()">Colorize</button>
<h3>Colorized Text</h3>
<pre id="newtext"></pre>
<script>
function colorize() {
var str = document.getElementById("origtext").value;
var newstr = str.replace(/(main)|(public)/gi, "<span style='color:red;'>main</span>");
document.getElementById("newtext").innerHTML = newstr;
}
</script>
Either use the same capture group and have the captured value go into the string, e.g.
var newstr = str.replace(
/(main|public)/gi,
"<span style='color:red;'>$1</span>"
);
Or use a function as the second arg of .replace
which has some choice logic, e.g.
var newstr = str.replace(
/(main)|(public)/gi,
function ($0, $1, $2) {
return "<span style='color:red;'>" + ($1 || $2) + "</span>";
}
);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments