Ga" /> Ga" /> Ga"/>

Trim string width jQuery

103 views Asked by At

How can I trim the string width so that it is no longer than 20 characters including spaces and ... to the end of the string?

<p class="streetname">Galloway Road, Bishop's Stortford</p>

Is there a jQuery method for this?

2

There are 2 answers

2
Ankit Agarwal On

You can use substr() function on the string value of that paragraph text:

var text = $('.streetname').text();
var newText = text.substr(0,17) + '...';
$('.streetname').text(newText)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="streetname">Galloway Road, Bishop's Stortford</p>

0
Christopher Supertramp On

You can do it like this:

if ($(".streetname").text().length > 20) {         
    $(".streetname").text($(".streetname").text().substring(0,50) + '...');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="streetname">This text is way to long to be displayed on the site so we just short it with jquery</p>

But if you recieve the text from php you can also short it there already..