0

Hi there is there a way to make a particular text bold for example

I have this #boldword and I want #boldword2 this two to be bold like this.

I have this word and I want word2 this two to be bold like this.

So as you can see the second example I want every word that has bold in front to become bold and the #bold to be removed.

I tried something so far

$.fn.wrapInTag = function(opts) {

  var tag = opts.tag || 'strong',
    words = opts.words || [],
    regex = RegExp(words.join('|'), 'gi'),
    replacement = '<strong>$&</strong>';

  return this.html(function() {
    return $(this).text().replace(regex, replacement);
  });
};

$('p').wrapInTag({
  tag: 'em',
  words: ['#boldworld']
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>The #boldworld is big and red.</p>
Community
  • 1
  • 1
Lila
  • 75
  • 1
  • 11

1 Answers1

0

As I understand it, you have a list of words you want bolding, which contain the prefix #bold. You want to remove the #bold prefix from your words?

All you need to do is add .replace('#bold', '') to your text.

Edit

Based on your comment, you want to change the regex so it matches any string that starts with #bold and embolden it?

The pattern I am using is (#bold([^\s\.]+)) - find any word beginning with #bold then capture everything up until a space or period ([^\s\.]+). The reason why the whole lot is in parenthesis is so that the whole string gets replaced. I've also changed the replacement string from $& to $2. The difference is, $& is similar to $1, in that it will place the whole matched string (e.g. #boldworld) into the text; while $2 will put in the inner matched text (i.e. what it matches in ([^\s\.]+), e.g. world).

For my own sanity, I've also removed the jquery call from the inner function and replaced it with vanilla javascript.

"use strict";
$.fn.wrapInTag = function() {
  //this = jQuery element
  return this.html(function() {
    //this = dom element
    return this.textContent
               .replace(/(#bold([^\s\.]+))/gi, '<strong>$2</strong>');
  });

};

$('p').wrapInTag();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>The #boldworld is big and #boldred.</p>
Community
  • 1
  • 1
Richard Parnaby-King
  • 14,703
  • 11
  • 69
  • 129