Anna Anna - 6 months ago 22
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 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice but how to implement this onto the website?

Answer

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

JavaScript

$("#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
})

HTML

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

fiddle

Comments