2016-07-14 16 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>

我改變了「串」正則表達式一點,因爲它更容易通過字符的負面名單不是積極的。

在正則表達式中進行替換的好處是,一旦你有一個匹配,那個子串就不會再匹配其他的東西(一個變量永遠不是字符串文字,反之亦然)。