2016-07-14 67 views
0

我正在JavaScript中编写PHP语法高亮显示代码。这是我曾尝试:JavaScript - 全局修饰符无法正常工作

<html> 
 

 
<head> 
 

 
    <title>Untitled 1</title> 
 

 
<script> 
 
function showContents(text) { 
 
    var string = /\"[[email protected]#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]*\"/i; 
 
    var aVariable = /\$([a-zA-Z0-9_\x7f-\xff]*)/i; 
 
    var output = text; 
 
    if(aVariable.test(output)==true) 
 
    { 
 
     output = output.replace(aVariable.exec(output)[0],"<font color='blue'>"+aVariable.exec(output)[0]+"</font>"); 
 
     document.getElementById("UserInput").innerHTML = output; 
 
    } 
 
    if(string.test(output)==true) 
 
    { 
 
     output = output.replace(string.exec(output)[0],"<font color='red'>"+string.exec(output)[0]+"</font>"); 
 
     document.getElementById("UserInput").innerHTML = output; 
 
    } 
 
    else 
 
    { 
 
     document.getElementById("UserInput").innerHTML = output; 
 
    } 
 
    document.write(output); 
 
} 
 
</script> 
 
</head> 
 

 
<body> 
 
<div id="UserInput"></div> 
 
<form> 
 
<textarea onkeyup="showContents(this.value)"></textarea></form> 
 

 
</body> 
 
</html>

上述脚本就像是做工精细的输入:

$name="ABC" 

但是,如果我尝试输入等:

$name="ABC";$name2="CDE" 

该代码仅突出显示第一个实例(即$name="ABC")。将修改器更改为全局不会给出输出本身。

+0

一旦你做了第一次替换,你有一个HTML字符串,而不是纯文本字符串。然后[它不再可能使用正则表达式来解析它](http://stackoverflow.com/a/1732454/1529630),以便做更多的替换。你需要一个合适的解析器,而不是正则表达式。 – Oriol

回答

0

问题是,与aVariable.exec(output)[0]你只返回第一场比赛,并将其传递给replace方法进行更换。由于此代码只执行一次,所以不会处理第二个匹配。

最好直接将正则表达式传递给replace而不是exec(它是一个字符串数组)的结果。此外,您还可以将回调函数传递至replace,以便您可以在每场比赛中执行代码,以便围绕font标签打包。

这里是一个工作片段:

function htmlEncode(text) { 
 
    // Uses the DOM to correctly escape HTML special characters (e.g. ampersand, less-than) 
 
    var elm = document.createElement('span'); 
 
    elm.textContent = text; 
 
    return elm.innerHTML; 
 
} 
 

 
function formatContents(text) { 
 
    // Use one regexp for all, and modify the matches with a call back function: 
 
    return text.replace(/(\"(\\"|.)*?\")|(\$([\w\x7f-\xff]*))/g, function (match, str, vari) { 
 
     var color = str ? 'red' : 'blue'; 
 
     return "<font color='" + color + "'>" + htmlEncode(match) + "</font>"; 
 
    }); 
 
} 
 

 
function showContents() { 
 
    // Take contents from textarea and display formatted in UserInput div: 
 
    document.getElementById("UserInput").innerHTML = 
 
     formatContents(document.getElementById("input").value); 
 
} 
 

 
document.getElementById("input").oninput = showContents; 
 
// Apply upon page load 
 
showContents();
The formatting is done as you type:<br> 
 
<textarea id="input" style="width:100%">$name="ABC"; 
 
$name2="CDE"</textarea> 
 
<div id="UserInput" style="white-space: pre"></div>

我改变了“串”正则表达式一点,因为它更容易通过字符的负面名单不是积极的。

在正则表达式中进行替换的好处是,一旦你有一个匹配,那个子串就不会再匹配其他的东西(一个变量永远不是字符串文字,反之亦然)。