设置用双引号括起来的单词的CSS

时间:2012-04-16 22:29:50

标签: javascript jquery html css string

这是关于Setting the CSS of code if it contains a reserved word的问题的后续问题。

我想做什么:如果某些代码有引号或双引号,我想将字体的颜色设置为红色和粗体。防爆。 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 个答案:

答案 0 :(得分:3)

为什么在执行简单的全局正则表达式查找和替换时分割字符串:

<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>

编辑:刚更新它以适应嵌套引号。

答案 1 :(得分:2)

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

我已设置a demonstration that works(更新后的链接以包含嵌套引号)。

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

<强>的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(""));
});

答案 2 :(得分: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("");
}

答案 3 :(得分: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>