[英]JavaScript – Issue using multiple keywords with RegExp
I'm trying to make a syntax highlighting system for Java code using JavaScript.我正在尝试使用 JavaScript 为 Java 代码制作一个语法高亮系统。 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?
如何为多个关键字执行 JavaScript RegExp 并仍然保留我的文本? Code: http://jsfiddle.net/vtnd02e7/
代码: 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, eg使用相同的捕获组并将捕获的值放入字符串中,例如
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, eg或者使用一个函数作为
.replace
的第二个参数,它有一些选择逻辑,例如
var newstr = str.replace(
/(main)|(public)/gi,
function ($0, $1, $2) {
return "<span style='color:red;'>" + ($1 || $2) + "</span>";
}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.