Raj
Raj

Reputation: 165

How to highlight the first 10 characters of text using Javascript or jQuery?

I want to highlight the first 10 characters of text and also color occurrences of the word "paragraph".

<html>
 <body>
  This is a heading
  This is a paragraph.This is another paragraph.
 </body>
</html>

Upvotes: 1

Views: 1561

Answers (2)

Fatima Zohra
Fatima Zohra

Reputation: 2967

Try this code in JS.

<!DOCTYPE html>
    <html>
    <body>

    <p>Click the button to highlight.</p>

    <p id="demo">This is a heading. This is a paragraph. This is another paragraph.</p>

    <button onclick="myFunction()">Try it</button>

    <script type="text/javascript">
    function myFunction()
    {
        var str= document.getElementById("demo").innerHTML;
        var str1 = "";

        for(var i = 0; i < 10; i++) {
            str1 += str[i];
        }
    var n=str.replace(str1,'<span style="font-weight: bold;">' + str1 + '</span>');
    document.getElementById("demo").innerHTML=n;
    }
    </script>

    </body>
    </html>

Upvotes: 1

M. Ahmad Zafar
M. Ahmad Zafar

Reputation: 4939

Considering this as your HTML content:

<div id="contents">
    This is a heading
    This is a paragraph.This is another paragraph.
</div>

This jQuery code will do what you desired:

$(document).ready(function() {
    var data = $('#contents').text().trim();

    var str = "";

    for(var i = 0; i < 10; i++) {
        str += data[i];
    }

    data = data.replace( /paragraph/g, '<span style="font-weight: bold;">paragraph</span>' );
    data = data.replace( str, '<span style="background-color: yellow;">' + str + '</span>' );

    $('#contents').html( data );
});

Upvotes: 4

Related Questions