包裹一个字符串的前几个单词

时间:2018-04-02 19:32:30

标签: javascript jquery

我有一个字符串,我需要从这个字符串开始包含几个单词,这些第一个单词的数量总是不同。我可以得到前几个单词的子字符串,但不能将它包装在span中。如何在每个字符串中包装每个子字符串?

$('.title-js').each(function(){
    var titleText = $(this).text().trim();
    var $wordLength = parseInt($.trim($(this).text()).split(' ').length);
    var half = $wordLength/2;
    var halfString = titleText.split(' ').slice(0,half).join(' ');

    $(halfString).wrap("<span class = 'golden-words'></span>"); //here is a problem

    $(this).html(function(_,txt) {
        return txt.replace(/(.$)/, "<span class = 'golden-words'>$1</span>");
    });

});
.golden-words {
  color: gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class = "title title-js">Some text part first.</div>
<div class = "title title-js">Some text part second!</div>
<div class = "title title-js">Some text part third?</div>
<div class = "title title-js">Some text part fourth)</div>

1 个答案:

答案 0 :(得分:1)

您从未将元素的内容分配给halfString,也未将其与另一半内容合并。 txt.replace正则表达式只匹配一个字符(.)和字符串结尾($)。

这应该有效:

$('.title-js').each(function(){
    var parts = $.trim($(this).text()).split(' ');
    
    var half = parts.length / 2;
    var firstHalf = parts.slice(0,half).join(' ');
    var secondHalf = parts.slice(half).join(' ');

    $(this).html("<span class = 'golden-words'>"+firstHalf+"</span> " + secondHalf);


});
.golden-words {
  color: gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class = "title title-js">Some text part first.</div>
<div class = "title title-js">Some text part second!</div>
<div class = "title title-js">Some text part third?</div>
<div class = "title title-js">Some text part fourth)</div>