1

これは、予約語が含まれている場合のコードの CSS の設定に関する私の質問へのフォローアップの質問です。

私がやろうとしていること: 一部のコードに引用符または二重引用符が含まれている場合、フォントの色を赤と太字に設定したいと考えています。元。 System.out.println( "Hello world" ); 「Hello world」を赤に設定する必要があります。

何が問題なのか: 最善を尽くしたにもかかわらず、制御ステートメントを適切に機能させることができないようです (少なくとも、それが問題だと思います)。最初の二重引用符以降を赤に設定しますが、単語がanyword"またはanyword'に等しいときに停止するように指示すると、ブロック内の残りのコードが赤に設定されます。

HTML

<html>
    <body>
        <code id="java">
            public static void main(String[] args)<br>
            {
            <pre>    int i = 120; </pre><br>
            <pre>    // Displays a message in the console </pre>
            <pre>    // This is a test </pre>
            <pre>    System.out.println( "Hello Big World!" );</pre>
            }
        </code>
    </body>
</html>

CSS

.quotes
{
    font-weight: bold;
    color: #E01B1B;
}

jQuery

$(document).ready(function() {
    var code  = $("#java").html(); // Get the code
    var split = code.split(' ');   // Split up each element
    var chkQ  = 0;                 // Check for quotes
    var chkC  = 0;                 // Check until end of comment line

    // Set the CSS of reserved words, digits, strings, and comments
    for (var j = 0; j < split.length; j++) {
        // Check to see if chkQ is set to true
        if (chkQ == 1) {
            // If the element matches (anyword") or (anyword'), then set
            // flag to false and continue checking the rest of the code.
            // Else, continue setting the CSS to .quotes
            if (split[j].match(/."/) || split[j].match(/.'/)) {
                split[j] = '<span class="quotes">' + split[j] + '</span>';
                chkQ = 0;
            } else {
                split[j] = '<span class="quotes">' + split[j] + '</span>';
            }
        }
        ...
        } else if (chkQ == 0 && chkC == 0) {
            ...
            // If the element matches a ("anyword) or ('anyword)...
            } else if (split[j].match(/"./) || split[j].match(/'./)) {
                split[j] = '<span class="quotes">' + split[j] + '</span>';
                chkQ = 1;
            } ...
        }
    }
    // Join all the split up elements back together!
    $("#java").html(split.join(' '));
});

質問: これは単なる正規表現、制御ブロック、またはまったく別の問題ですか?

4

4 に答える 4

4

単純なグローバル正規表現の検索と置換を実行できるのに、なぜ文字列を分割するのですか?

<script type="text/javascript">
$(document).ready(function(){
//cache the element
   el = $('#java');
//get the HTML contained within the cached element
   code = el.html();
//return the code having executed the replace method, regex explained:
/*    
([^\w]{1}) -> look for a single character that is not an alpha character
(["']) -> then look for either a single quote or double quote
(.*?) -> then look any character, but don't be greedy
(\2) -> then look for what was found in the second group - " or '
([^\w]{1}) -> and finally look for a single character that is not an alpha character
*/
    code = code.replace(/([^\w]{1})(["'])(.*?)(\2)([^\w]{1})/gm,
//execute an anonymous callback, passing in the result for every match found
    function(match, $1, $2, $3, $4, $5, offset, original) {
//construct the replacement
        str =  $1 + '<span class="quotes">' + $2 + $3 + $4 + '</span>' + $5; 
//return the replacement
        return str; 
    });
//replace the existing HTML within the cached element
   el.html(code);
});
</script>

編集:ネストされた引用符に対応するように更新しました。

于 2012-04-16T23:33:52.970 に答える
2

あなたの要件をすべて知っているわけではありませんが、一重引用符が少し複雑になる可能性があります。

機能するデモをセットアップしました(ネストされた引用符を含めるようにリンクを更新しました)。

バグがないことを保証するものではありません。置換は 2 段階で行われます。最初は二重引用符、次に単一引用符で、潜在的なアポストロフィを除外しようとします (以下のコードでは、アポストロフィのフィルターは一般的な後続の文字に基づいていることに注意してください。実際に必要な数はわかりませんが、もしあれば)。

Javascript

$(document).ready(function() {
    var code  = $("#java").html(); // Get the code
    var split = code.split('\"');  // Split up each element at the "

    // Set the CSS of reserved words, digits, strings, and comments
    for (var j = 0; j < split.length - 1; j++) {
        if (j%2 == 0) { //if first, add beginning
            split[j] = split[j] + '<span class="quotes">"';
        } else {//if second, add ending
            split[j] = split[j] + '"</span>';
        }
    }
    // Join all the split up elements back together!
    $("#java").html(split.join(""));

    code  = $("#java").html(); // Get the code
    split = code.split('\'');  // Split up each element at the '
    var openQ = 1;
    var sub1;
    var sub2;

    for (var j = 0; j < split.length - 1; j++) {
        sub1 = split[j+1].substr(0,2); //checking for a contraction of 's
        sub2 = split[j+1].substr(0,3); //checking for a contraction of 'll
        if(sub1 != "s " && sub2 != "ll ") {
          if (openQ) { //if first, add beginning
            split[j] = split[j] + '<span class="quotes">\'';
            openQ = 0;
          } else {//if second, add ending
            split[j] = split[j] + '\'</span>';
            openQ = 1;
          }
        }
        else {//add apostrophe back
            split[j] = split[j] + '\'';
        }
    }
    $("#java").html(split.join(""));
});
于 2012-04-17T00:09:21.470 に答える
0

純粋な JavaScript バージョンは次のとおりです。
id= 引用符付きの要素の ID
classid= 引用符に追加するクラス

function quotes(id,classid) {
    var code  = document.getElementById(id).innerHTML; 
    var split = code.split('\"'); 
    for (var j = 0; j < split.length - 1; j++) {
        if (j%2 == 0) { 
            split[j] = split[j] + '<span class='+classid+'>"';
        } else {
            split[j] = split[j] + '"</span>';
        }
    }
    document.getElementById(id).innerHTML = split.join("");
    code  = document.getElementById(id).innerHTML;
    split = code.split('\'');
    var openQ = 1;
    var sub1;
    var sub2;
    for (var j = 0; j < split.length - 1; j++) {
        sub1 = split[j+1].substr(0,2);
        sub2 = split[j+1].substr(0,3);
        if(sub1 != "s " && sub2 != "ll ") {
          if (openQ) {
            split[j] = split[j] + '<span class='+classid+'>\'';
            openQ = 0;
          } else {
            split[j] = split[j] + '\'</span>';
            openQ = 1;
          }
        }
        else {
            split[j] = split[j] + '\'';
        }
    }
    document.getElementById(id).innerHTML = split.join("");
}
于 2016-06-04T21:49:46.410 に答える