Home >Web Front-end >CSS Tutorial >How Can I Bold Specific Text Strings Within a Paragraph Using jQuery?

How Can I Bold Specific Text Strings Within a Paragraph Using jQuery?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-30 12:04:12382browse

How Can I Bold Specific Text Strings Within a Paragraph Using jQuery?

Bolding Text Strings in jQuery

You are seeking a jQuery solution to highlight a specific text string within a paragraph by bolding it. However, your code is not producing the desired result:

$(window).load(function() {
  // ADD BOLD ELEMENTS
  $('#about_theresidency:contains("cross genre")').css({'font-weight':'bold'});
});

This code aims to target the text with the phrase "cross genre" within the element with the ID "about_theresidency" and apply the CSS property "font-weight" to make it bold. However, it remains ineffective.

Solution

To bold text strings using jQuery, you can employ the replace() method along with html(). The following code demonstrates how:

var html = $('p').html();
$('p').html(html.replace(/world/gi, '<strong>$&amp;</strong>'));

This code snippet:

  1. Stores the HTML content of the paragraph in the html variable.
  2. Uses the replace() method on html to find all occurrences of the text "world" (case-insensitive) and wraps it within tags.
  3. Updates the HTML content of the paragraph with the modified string to apply the bold formatting.

Additional Tip

The code can be refined into a plugin:

$.fn.wrapInTag = function(opts) {

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

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

// Usage
$('p').wrapInTag({
  tag: 'em',
  words: ['world', 'red']
});

This plugin allows you to wrap specific words in HTML tags. In the example provided, it wraps the words "world" and "red" in tags.

The above is the detailed content of How Can I Bold Specific Text Strings Within a Paragraph Using jQuery?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn