$ .each()使用repeat()向每行添加制表符空格

时间:2017-02-13 05:16:32

标签: javascript jquery

我正在处理我的jQuery语法高亮脚本,我想实现一个美化器,它可以缩小代码,然后通过在需要的地方添加新行和制表符来美化它。

我目前正在CSS部分工作,但我在向{}之间的每一行添加标签空间时遇到了问题。< / p>

实例:

> View On CodePen

&GT;查看

&#13;
&#13;
code = $(".input").html().trim();

if (code) {
  code = code
    // REMOVE TAB SPACES
    .replace(/(    )/gi,'')
    // REMOVE NEW LINES
    .replace(/[\n\r]/g,'')
    // REMOVE SPACES BETWEEN SECTIONS
    .replace(/(;|{|})(\s+)([^ \s+])/g,'$1$3')
    .replace(/(;|{|})(\s+)([^ \s+])/g,'$1$3')
    .replace(/(\*\/)(\s+)([^ \s+])/g,'$1$3');
}
$('.minified').text(code);

minified = $('.minified').html();

if (minified) {
  minified = minified
    .replace(/(\;|\}|\{)/gi,'$1\n\r')
    .replace(/((\/\*)(| )([^"'\s\n]+)(| )(\*\/))/gi,'\n\r$1\n\r');
  
  var level = 0;
  var lines = minified.split("\n");
  $.each(lines, function(n, elem) {
    last = elem[elem.length -1]
    if (last === "{") { level = level + 1; }
    else if (last === "}") { level = level - 1; }
    else {
      var tab = "    ".repeat(level);
      elem = tab + elem;
    }
  });
}
$('.beautified').text(minified);
&#13;
.wrap {
  float:left;
  width: 400px;
  margin: 20px;
}
.wrap > h1 {
  text-align: center;
}
pre {
  float: left;
  width:100%;;
  height: 400px;
  border: 1px solid #000000;
  overflow: auto;
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="wrap">
  <h1>INPUT</H1>
  <pre class="input">
  div.highlight { 
      background:#FFFFFF;
      border:1px solid #E0E0E0;
      font-family:"Courier New",Courier,monospace;
      overflow: hidden;
  }
  div.highlight pre{
      width: 100%;
      overflow: auto;
      padding:0;
      margin:0;
      font-size:13px;
      clear: both;
  }

  /* tabs */
  div.highlight ul.tabs {
      overflow: hidden;
      padding: 5px 0 5px 0;
      margin: 0;
      list-style: none;
      border-bottom: 1px solid #E0E0E0;
      width: 100%;
  }
  div.highlight ul.tabs li {
      padding: 0;
      margin: 0 5px;
      float: left;
      background: none;
      border-bottom: 1px dashed #CCC;
      line-height:1.0em;
      color: #CCC;
      cursor: pointer;
  }
  div.highlight ul.tabs li.active {
      border-bottom: none;
      cursor: default;
  }
  div.element {
      flex-direction: row;
      flex-wrap: nowrap;
      flex-flow: column-reverse wrap;
  }
  </pre>
</div>
<div class="wrap">
  <h1>MINIFIED</H1>
  <pre class="minified"></pre>
</div>
<div class="wrap">
  <h1>BEAUTIFIED</H1>
  <pre class="beautified"></pre>
</div>
&#13;
&#13;
&#13;

问题

  1. 如何正确遍历每一行,如果该行没有以开口({)或结束(})花括号结尾,请将代码缩进至一个标签我们的四个空格由level计算?
  2.   

    更新1)。仅适用于CSS一次缩进的正则表达式的工作版

         

    但是,此版本仅适用于一个缩进和CSS   我想让我的其他版本用于其他语言   并进一步缩进@media个查询,进一步缩进代码   内:

         

    > Example on CodePen

         

    &GT;以下示例

         

    &#13;
    &#13;
    > 
    >     code = $(".input").html().trim();
    > 
    >     if (code) {
    >       code = code
    >         // REMOVE TAB SPACES
    >         .replace(/(    )/gi,'')
    >         // REMOVE NEW LINES
    >         .replace(/[\n\r]/g,'')
    >         // REMOVE SPACES BETWEEN SECTIONS
    >         .replace(/(;|{|})(\s+)([^ \s+])/g,'$1$3')
    >         .replace(/(;|{|})(\s+)([^ \s+])/g,'$1$3')
    >         .replace(/(\*\/)(\s+)([^ \s+])/g,'$1$3');
    >     }
    >     $('.minified').text(code);
    > 
    >     minified = $('.minified').html();
    > 
    >     if (minified) {
    >       minified = minified
    >         .replace(/(\;|\}|\{)/gi,'$1\n\r')
    >         .replace(/((\/\*)(| )([^"'\s\n]+)(| )(\*\/))/gi,'\n\r$1\n\r')
    >         .replace(/(([a-zA-Z0-9 -]+)(:)([a-zA-Z0-9 -#%"-., ]+)(;))/g,'    $1');
    >     }
    >     $('.beautified').text(minified);
    > 
    > 
    &#13;
    > 
    >     .wrap {
    >       float:left;
    >       width: 400px;
    >       margin: 20px;
    >     }
    >     .wrap > h1 {
    >       text-align: center;
    >     }
    >     pre {
    >       float: left;
    >       width:100%;;
    >       height: 400px;
    >       border: 1px solid #000000;
    >       overflow: auto;
    >     }
    > 
    >     pre.minified {
    >       height: 50px;
    >     }
    > 
    > 
    &#13;
    > 
    >     <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    >     <div class="wrap">
    >       <h1>INPUT</H1>
    >       <pre class="input">
    >       div.highlight { 
    >           background:#FFFFFF;
    >           border:1px solid #E0E0E0;
    >           font-family:"Courier New",Courier,monospace;
    >           overflow: hidden;
    >       }
    >       div.highlight pre{
    >           width: 100%;
    >           overflow: auto;
    >           padding:0;
    >           margin:0;
    >           font-size:13px;
    >           clear: both;
    >       }
    > 
    >       /* tabs */
    >       div.highlight ul.tabs {
    >           overflow: hidden;
    >           padding: 5px 0 5px 0;
    >           margin: 0;
    >           list-style: none;
    >           border-bottom: 1px solid #E0E0E0;
    >           width: 100%;
    >       }
    >       div.highlight ul.tabs li {
    >           padding: 0;
    >           margin: 0 5px;
    >           float: left;
    >           background: none;
    >           border-bottom: 1px dashed #CCC;
    >           line-height:1.0em;
    >           color: #CCC;
    >           cursor: pointer;
    >       }
    >       div.highlight ul.tabs li.active {
    >           border-bottom: none;
    >           cursor: default;
    >       }
    >       div.element {
    >           flex-direction: row;
    >           flex-wrap: nowrap;
    >           flex-flow: column-reverse wrap;
    >       }
    >       </pre>
    >     </div>
    >     <div class="wrap">
    >       <h1>MINIFIED</H1>
    >       <pre class="minified"></pre>
    >     </div>
    >     <div class="wrap">
    >       <h1>BEAUTIFIED</H1>
    >       <pre class="beautified"></pre>
    >     </div>
    > 
    > 
    &#13;
    &#13;
    &#13;

2 个答案:

答案 0 :(得分:3)

你很亲密。在您拥有的代码中,elem是您传递给each的函数内的局部变量。您将其修改为缩​​进,但是当函数在迭代结束时返回时,程序会忘记它。您可能希望将其分配回lines,可能会使用lines[n] = elem。修改:$.map可能更合适。

然后,出现相同问题的另一种变体。 lines已更新,但minified仍然相同。您可以使用minified = lines.join('\n')将这些部分粘合在一起并更新minified

答案 1 :(得分:1)

您的缩进算法由于各种原因无效。

1)您需要像lines这样写入lines[n] = tab + elem;数组:minified
2)您错误地将lines而不是$('.beautified')分配给了$.each(lines, function(n, elem) { var last = elem[elem.length -1]; if (last === "}") { level--; } var tab = " ".repeat(level); lines[n] = tab + elem + "\n"; if (last === "{") { level++; } }); lines = lines.join(''); $('.beautified').text(lines); 3)您的代码没有缩进超过1级。我修改它以在任何深度缩进,并添加了一个codepen示例来演示这一点。

class myclass:
    sample=0
    white=0
    black=0
    gray=0
    others=0
    colorlist=["white", "black", "gray"]
    def __init__(self):
        print("what is your name?")
        myclass.name=input()
        print("What is the color of your car?")
        myclass.color= input()
        myclass.sample=myclass.sample+1
    def check_color(self):
            if myclass.color in myclass.colorlist:
            if myclass.color == myclass.colorlist[0]:
                myclass.white= myclass.white+1
            elif myclass.color == myclass.colorlist[1]:
                myclass.black=myclass.black+1
            else:
                myclass.gray = myclass.gray+1
        else:
           myclass.others=myclass.others+1
    def display_result(self):
        print ("Hello," ,myclass.name)
        print ("The number of white cars are:", myclass.white)
        print ("The number of black cars are:", myclass.black)
        print ("The number of gray cars are:", myclass.gray)
        print ("The number of other colored cars are:", myclass.others)
        print ("The number samples are:", myclass.sample)
var=0
mylist=[]
while var<4:
    mylist.append(myclass())
    mylist[var].check_color()
    mylist[var].display_result()
    var=var+1

http://codepen.io/anon/pen/NdezxM