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"
)。修飾子をグローバルに変更しても、出力自体は提供されません。
最初に置換すると、プレーンテキスト文字列ではなくHTML文字列が使用されます。そして、それは[これを解析するために正規表現を使うことはもはや不可能です](http://stackoverflow.com/a/1732454/1529630)。正規表現ではなく適切なパーサーが必要です。 – Oriol