James
James

Reputation: 1706

Selected text and making bold apart from first word using jQuery

I know this is something very simple but I am still new to jQuery, so I'm a little unsure how to approach. I have found a good 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 <strong> but excluding the first word.

Upvotes: 0

Views: 274

Answers (1)

nnnnnn
nnnnnn

Reputation: 150080

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.

Upvotes: 3

Related Questions