-1

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?

Reece
  • 2,581
  • 10
  • 42
  • 90
  • Please add a reason for the down vote. I will try to fix the issue – Reece Jul 17 '18 at 11:52
  • 1
    Questions should include some indication of an attempt to resolve the issue (code that we can fix), or at least explain what research you've done, otherwise it's just *"write my code for me nao"*, which is not what Stack Overflow is for. Note - I didn't downvote, but will if you don't make the question good :) – Reinstate Monica Cellio Jul 17 '18 at 11:53

2 Answers2

0

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>
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
0

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..