JavaScript - 全局修饰符无法正常工作

时间:2016-07-14 17:52:33

标签: javascript html

我正在用JavaScript编写PHP语法高亮显示器代码。这是我尝试过的:



chown root:root /var/empty/sshd




以上脚本适用于以下输入:

<html>

<head>

    <title>Untitled 1</title>

<script>
function showContents(text) {
    var string = /\"[a-z0-9A-Z!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]*\"/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" )。将修饰符更改为全局不会自动提供输出。

1 个答案:

答案 0 :(得分:0)

问题在于aVariable.exec(output)[0]只返回第一个匹配项,并将其传递给replace方法进行替换。由于此代码仅执行一次,因此永远不会处理第二个匹配。

最好将正则表达式直接传递给replace而不是exec(这是一个字符串数组)的结果。此外,您还可以将回调函数传递给replace,这样您就可以在每个匹配项上执行代码,以便在其周围包装font标记。

这是一个工作片段:

&#13;
&#13;
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();
&#13;
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>
&#13;
&#13;
&#13;

我更改了&#34;字符串&#34;正则表达式,因为传递负面的字符列表而不是正面的字符列表。

在正则表达式中执行替换的优点是,一旦匹配,该子字符串将不再与其他内容匹配(变量永远不是字符串文字,反之亦然)。

相关问题