javascript - 在元素中查找行,然后用 <span> 标签将其包裹起来

标签 javascript jquery html

我需要编写一段代码,用 br 分割 html,找到以数字开头的行,然后添加 span 标签。

jQuery(document).ready(function($) {
    var brExp = /<br\s*\/?>/i;
    var swn = /^[0-9]+[^)]/;
    var lines = $('.caption').html().split(brExp).filter(line => swn.test(line.trim()));;
    jQuery.each(lines, function() {
        console.log(this);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="caption">
    BBQ Porked Rolls.

    Ingredients:
    3 to 4 pounds pork shoulder<br />
    1 tablespoon salt<br />
    2 tablespoons brown sugar<br />

    STEPS:
    In the oven,... 
<div>

我已经得到了这些行,剩下的就是在这些行周围添加 span 标签,而不需要为结果创建一个新的 div。也许通过使用 replace()wrap() 或完全其他的东西。这就是我需要帮助的地方。

预期输出:

<span itemprop="recipeIngredient">3 to 4 pounds pork shoulder</span><br>
<span itemprop="recipeIngredient">1 tablespoon salt</span><br>
<span itemprop="recipeIngredient">2 tablespoons brown sugar</span><br>

谢谢

最佳答案

您只需要map()超过集合。

jQuery(document).ready(function($) {
  var brExp = /<br\s*\/?>/i;
  var swn = /^\d/;
  var lines = $('.caption').html().split(brExp).map(function (line) {
        // strip the whitespace
        line = line.trim();
        // check for number
        if ( swn.test(line) ) {
          // add enclosing span
          line = '<span itemprop="recipeIngredient">' + line + '</span>';
        }
        // return the line for the new collection
        return line;
      }).join('<br />');
  $('.caption').html(lines);
});

如果您只想更改第一行,可以对代码进行以下细微更改:

jQuery(document).ready(function($) {
  var firstOnly = true; // will check for number when this value is true
  var brExp = /<br\s*\/?>/i;
  var swn = /^\d/;
  var lines = $('.caption').html().split(brExp).map(function (line) {
        // strip the whitespace
        line = line.trim();
        // check 'firstOnly' is true before checking for number
        if ( firstOnly && swn.test(line) ) {
          // add enclosing span
          line = '<span itemprop="recipeIngredient">' + line + '</span>';
          // first matching line has been modified
          // so set 'firstOnly' to false
          firstOnly = false;
        }
        // return the line for the new collection
        return line;
      }).join('<br />');
  $('.caption').html(lines);
});

关于javascript - 在元素中查找行,然后用 <span> 标签将其包裹起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50214465/

相关文章:

javascript - Firebase 管理员无法读取未定义的属性 'cert'

javascript - Jquery 表单提交不起作用,而是在控制台中收到 js 警告 'body.scrollLeft is deprecated in strict mode'

javascript - 让 div 滚动到页面顶部?

javascript - 如何使用 Chrome 控制台导航到 bing.com 并输入搜索文本?

html - 有没有办法禁止里面的元素去 "outside"

javascript - AngularJS:如何以表格形式每行表示和保存一个对象

javascript - 从 src 为外部域的 iframe 中,可以通过 "parent"对象使用哪些方法?

javascript - for循环中的两个条件

javascript - 为什么水平滚动时出现固定的div?

html - 在页面中重叠两个单独的 div