Anna Anna - 1 year ago 146
Javascript Question

Cut off last characters from html paragraph with JS

How to cut off last 20 characters from a normal html paragraph with a classname which contains two words? For instance

<p class="sentence slice">Last twenty characters have to be chopped off!!!</p>

I know there's a slice method in JS but how to implement this onto the website?

Answer Source

If you are interested in using .slice, all you need to do is this:


$("#clickme").click(function () {
    var text = $("p").text();
    text = (text.length > 20) ? text.slice(0,-20) : text;
    // important to check whether the text is longer than 20 characters
    $("p").text(text);  // update the text


<p>Lots and lots and lots and lots and lots of text12345678901234567890</p>
<button id="clickme">remove last 20 characters</button>


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download