繁体   English   中英

有条件地换行<li>标签并删除第一个字符

[英]Conditionally wrap lines in <li> tags and remove first character

使用以下 html,我需要在以破折号开头的每一行周围包裹一个<li>标签,去除破折号,然后将整个列表包装在一个<ul>标签中。

<div class="json-content">
This line doesn't have a dash
This line also doesn't have a dash 
-An unordered list should start here because the line starts with a dash
-This line starts with a dash and has some dashes-in-the-middle
-Another line that starts with a dash
And another a line that doesn't have a dash.
</div>

我使用下面的代码( 基于之前的问题)来实现这一点,但是当 div 中有其他非虚线文本时,它也会在这些行周围添加一个<li>标记。 我知道问题的一部分是它首先剥离了破折号,但我尝试使用正则表达式测试仪来修改它,但我无法弄清楚。 我怎样才能做到这一点?

 $('.json-content').each(function() {
      var $this = $(this);

      $this.html(
        $this
          .html()
          .trim()
          .replace(/^-|[\r\n]+-/g, "\n")
          .replace(/[^\r\n]+/g, '<li class="item">$&</li>')    
          );
          $(this).find('li.item').wrapAll( "<ul class='json-list' />");  
    });

这是一个小提琴: https : //jsfiddle.net/9xd2vacj/2/

最终结果应如下所示:

这条线没有破折号
这条线也没有破折号

  • 无序列表应该从这里开始,因为该行以破折号开头
  • 这条线以破折号开头,中间有一些破折号
  • 另一行以破折号开头

还有一条没有破折号的线。

您可以附加连字符^[ \\t]*-.*以匹配以连字符开头的行。 然后在捕获组中捕获列表项并匹配 0+ 次空白字符和连字符。

(<li class="item">)\s*-

在替换中使用空字符串。

您的代码可能如下所示:

$('.json-content').each(function () {
    var $this = $(this);
    $this.html(
        $this
            .html()
            .trim()
            .replace(/^[ \t]*-.*/gm, '<li class="item">$&</li>')
            .replace(/(<li class="item">)\s*-/g, "$1")
    );
    $(this).find('li.item').wrapAll("<ul class='json-list' />");
});

更新的小提琴

 $('.json-content').each(function () { var $this = $(this); $this.html( $this .html() .trim() .replace(/^[ \\t]*-.*/gm, '<li class="item">$&</li>') .replace(/(<li class="item">)\\s*-/g, "$1") ); $(this).find('li.item').wrapAll("<ul class='json-list' />"); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="json-content"> This line doesn't have a dash This line also doesn't have a dash -An unordered list should start here because the line starts with a dash -This line starts with a dash and has some dashes-in-the-middle -Another line that starts with a dash And a line that doesn't start with a dash but has-one in the middle. </div>

你可以结合:

 $('.json-content').html(function (idx, oldhtml) { return oldhtml.replace(/\\n *-([^\\n]*)/g, function(match, p1) { return '<li>' + p1 + '</li>'; }) }).find('li').wrapAll("<ul/>");
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="json-content"> This line doesn't have a dash This line also doesn't have a dash -An unordered list should start here because the line starts with a dash -This line starts with a dash and has some dashes-in-the-middle -Another line that starts with a dash And another a line that doesn't have a dash. </div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM