如何从$(...)。html()方法给出的多行字符串中删除缩进

时间:2015-09-24 13:54:51

标签: javascript jquery string trim

$(element).html();返回给定元素的html及其所有缩进。

HTML

<body>
  <div>
    <section>
      <ol>
<!-- embeded comment with no indents -->
         <li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
         <li>Aliquam tincidunt mauris eu risus.</li>
         <li>Vestibulum auctor dapibus neque.</li>
      </ol>
    </section>
  </div>
</body>

js

$('section').html();

将返回

      <ol>
<!-- embeded comment with no indents -->
         <li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
         <li>Aliquam tincidunt mauris eu risus.</li>
         <li>Vestibulum auctor dapibus neque.</li>
      </ol>

如何删除缩进(如果可能,请缩进注释),以获得以下结果:

<ol>
  <!-- embeded comment with no indents -->
  <li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
  <li>Aliquam tincidunt mauris eu risus.</li>
  <li>Vestibulum auctor dapibus neque.</li>
</ol>

3 个答案:

答案 0 :(得分:1)

看看js-beautify。在嵌入之前,请尝试基于此库的http://jsbeautifier.org

答案 1 :(得分:0)

好的我已为此编写了自定义功能

function trimmedHtml(element){
  var html = $(element).html();

  // find shortest html element indent
  var shortestIndent;
  html = html.split('\n');
  for(var i = 0; i < html.length; i++){
    // for each line
    var line = html[i];
    // ignore comment lines in searching
    if( $.trim(line).substring(0, 4) != "<!--" ){
      // count number of spaces before code for current line
      var spaces = line.search(/\S/);
      if( (shortestIndent > spaces || shortestIndent == undefined) && spaces >= 0 ){
        shortestIndent = spaces;
      }
    }
  }

  // remove spaces before each line (align to shortest indent)
  for(var i = 0; i < html.length; i++){
    // for each line
    var line = html[i];
    if( $.trim(line).substring(0, 4) != "<!--" ){
      // if line is not a comment, remove spaces
      html[i] = line.substring(shortestIndent, line.length);
    } else {
      // if line is a comment:
      // remove it's spaces
      html[i] = $.trim(line);
      // align to shortest line, and add 2 spaces
      for (space = 0; space < 2; space++) {
        html[i] = " " + html[i];
      }
    }
  }

  // join all lines
  html = html.join("\n");
  return html;
}

然后用作:

console.log( trimmedHtml($('section')) );

答案 2 :(得分:0)

看到这个回复后,我明白编写自己的解决方案会更好,所以这里是:

function trimHtml(html){
  var htmlArray = html.split('\n'),
    htmlToRetun = [];

  return _.map(htmlArray,function(line){
      //per ogni linea trimmo 
      return jQuery.trim(line);
    }).join('\n');
}

此函数将从字符串返回未缩进的html。

我使用lodash来__map数组,但你可以使用javascript .map函数。