Remade
Remade

Reputation: 427

format character length/limit in JavaScript

I would like to have a custom string that is truncated after exceeding a given length and has an indicator showing that it has been shortened for example: "a very long string" to " a very l...". Thanks in advance

Upvotes: 1

Views: 551

Answers (2)

elclanrs
elclanrs

Reputation: 94131

You can use a simple regex, where 10 is the number of characters you want to have.

str = str.replace(/(.{10}).*/, '$1...');

It can be abstracted like:

function truncate(str, len) {
  return str.replace(new RegExp('(.{'+ len +'}).*'), '$1...');
}

var str = 'Lorem ipsum dolor sit amet consectetur';
console.log(truncate(str,10)); //=> "Lorem ipsu..."

Upvotes: 3

Khanh TO
Khanh TO

Reputation: 48982

function truncateString(value, maxLength){
      var returnedValue = value;
      if (returnedValue.length > maxLength){
          returnedValue = returnedValue.substring(0,maxLength) + "...";
      }
      return returnedValue;
}

Upvotes: 2

Related Questions