代码之家  ›  专栏  ›  技术社区  ›  geoplous

选择html标记中的前两个单词并添加选择器

  •  0
  • geoplous  · 技术社区  · 7 年前

    我使用此脚本选择容器中的第一个单词:

    $(".article-title").html(function(){
        var text= $(this).text().trim().split(" ");
        var first = text.shift();
        return (text.length > 0 ? "<span class='special'>"+ first + "</span> " : first) + text.join(" ");
    });
    

    如何选择前2或3个单词?

    谢谢你

    2 回复  |  直到 7 年前
        1
  •  2
  •   Kartikeya Khosla    7 年前

    你可以这样做。

    $(".article-title").html(function(){
        var text= $(this).text().trim().split(" "); //.split() returns an array.
        var first = text[0];
        var second = text[1];
        return (text.length > 0 ? "<span class='special'>"+ first + " " + second + "</span>" : first) + text.slice(2).join(" ");
    });
    

    编辑:

    Working Fiddle

        2
  •  1
  •   Sooriya Dasanayake    7 年前

    试试这个。。你可以从你的段落中得到前n个单词

    $('.article-title').html(function (i, html) {
        return html.replace(/(\w+\s\w+)/, '<span>$1</span>')
    });
    <div class="article-title"> this is: a title of the article</div> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>