Q:

wrap first few words of a string

I have a string and I need to wrap in span first few words from this strings, the number of these first words always be different. I can get the substring of first few words, but can't wrap it in span. How can I wrap every substring in every string?

$('.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>

A:

You never assigned the contents of the element to halfString, nor combined it with the other half of the contents. The txt.replaceregex only matches one character (.) and the end of the string ($).
This should work:

$('.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>

