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

我不知道您的所有要求,但您的单引号似乎有点复杂。

我已经建立了一个有效的演示(更新链接以包含嵌套引号)。

我不保证它没有错误。它分两个阶段进行替换,首先是双引号,然后是单引号,试图清除潜在的撇号(请注意,在下面的代码中,撇号的过滤器基于常见的后续字母 - 不确定您实际上可能需要多少个,如果有)。

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 回答
0

String.prototype.Text2Html = function (){
  var div = document.createElement('div');
  div.appendChild(document.createTextNode(this))
  encoded=div.innerHTML;
  div.remove();
  return encoded
}

String.prototype.colorTheQuotes = function(){
  
  var re     = /(?:<span style=|)(?:(?:"[^"]*")|(?:'[^']*'))/gm,
      text   = this.Text2Html(),
      output = text,
      tour   = 0,
      slen   = 27;

    while ((match = re.exec(text)) != null) {
      if(match[0].startsWith("<span")) continue
      output=output.slice(0,match.index+tour*slen)+'<span class="quote">'+output.slice(match.index+tour*slen,match.index+match[0].length+tour*slen)+"</span>"+output.slice(match.index+match[0].length+tour*slen);tour++
    }
  return output
}

element=document.getElementById("color")
document.addEventListener("readystatechange",(e)=>{
  element.innerHTML=element.innerText.colorTheQuotes();
 })
.quote{
  color: red;
}
<span>System.out.println( "Hello world" );</span><br>
<span id="color">System.out.println( "Hello world" );</span>

于 2021-07-08T18:34:39.577 回答