James James - 3 months ago 15
jQuery Question

jQuery: Selected text and making bold apart from first word

Know this is something very simple but still new to jQuery so a little unsure how to approach... I have found a goof few solutions with making the first word bold but not what i need...

I want to only make the words bold other than the first word... is this possible?

I.E

Buy This Product

to be

Buy This Product

I only have a example from another solution for the first word but not sure how to adjust...

$('.homepage-boxes .ty-banner__image-wrapper a').find('.ty-btn_ghost').html(function(i, h){
return h.replace(/\w+\s/, function(firstWord){
return '<strong>' + firstWord + '</strong>';
});
});


I have adjusted with the classes i need and the find class but i want to make the text but excluding the first word.

Thanks for anyone's help on this

Answer

There are a few ways to do this. You could use a regex like / (.*)/ to match the first space followed by every other character to the end of the string as a sub match:

$('.homepage-boxes .ty-banner__image-wrapper a').find('.ty-btn_ghost').html(function(i, h){
  return h.replace(/ (.*)/, " <strong>$1</strong>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- html structure improvised to match the selectors from the question's JS -->
<div class="homepage-boxes">
  <div class="ty-banner__image-wrapper">
    <a><span class="ty-btn_ghost">Buy This Product</span></a>
  </div>
  <div class="ty-banner__image-wrapper">
    <a><span class="ty-btn_ghost">Buy The Other Product</span></a>
  </div>
  <div class="ty-banner__image-wrapper">
    <a><span class="ty-btn_ghost">Buy Some Third Product</span></a>
  </div>
</div>

Note that using parentheses in the regex allows you to refer to the matched bit using $1, so you can provide the replacement as a string in the second argument to .replace() rather than passing a function.