Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu February 20, 2024 . #jQuery . #Q&A

Write a jQuery code to make first word of each statement to bold

To make the first word of each statement bold using jQuery, you can loop through each element containing the statements and apply a CSS style to the first word. Here's an example of how you can achieve this:

<p class="statement">This is a paragraph.</p>
<p class="statement">This is a paragraph 2.</p>
   
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
    $(document).ready(function(){
    // Select all elements containing statements
     $('.statement').each(function(){
        // Split the text content into words
        var words = $(this).text().split(' ');
        // Get the first word
        var firstWord = words.shift();
        // Wrap the first word in a <span> element with a bold style
        $(this).html('<span style="font-weight: bold;">' + firstWord + '</span> ' + words.join(' '));
     });
    });
</script>

In this jQuery code, we first wait for the document to be ready. Then, we select all elements with the class statement using the jQuery selector.

We iterate over each of these elements using the each() function. Inside the loop, we split the text content of the element into an array of words using the split() function.

Then we shift the first word from the array and store it in a variable. Next, we wrap this first word in a <span> element with a bold style using the html() function. Finally, we concatenate the remaining words back together and update the content of the element.

save
listen
AI Answer
1 Answer
  1. Another way to achieve the same result is by using regular expressions to find and replace the first word of each statement with a bold version of itself. Here's how you can do it:
    // Select all elements containing statements
    const statements = document.querySelectorAll('.statement');

    // Loop through each statement element
    statements.forEach(statement =>{
        // Get the text content of the statement
    let text = statement.textContent.trim();

        // Use a regular expression to replace the first word with a bold version
        text = text.replace(/^(\w+)/, '<strong>$1</strong>');

        // Update the HTML content of the statement element
        statement.innerHTML = text;
    });

    This alternative approach uses a regular expression (/^(\w+)/) to find the first word of each statement and then replaces it with a bold version using the <strong> tag.
    Reply Delete
    Share
Write Your Answer
loading
back
View All