- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Limiting string up to a specified length in JavaScript
Problem
We are required to write a JavaScript function that takes in a string and a number. Our function should return the truncated version of the given string up to the given limit followed by "..." if the result is shorter than the original string otherwise our function should return the same string if nothing was truncated.
Example
Following is the code −
const str = 'Testing String'; const num = 8; const limitString = (str = '', num = 1) => { const { length: len } = str; if(num < len){ return str.slice(0, num) + '...'; }else{ return str; }; }; console.log(limitString(str, num));
Output
Following is the console output −
Testing ...
- Related Articles
- Generating random string of specified length in JavaScript
- Limiting elements occurrences to n times in JavaScript
- Limiting duplicate character occurrence to once in JavaScript
- How can we retrieve the length of a specified string in MySQL?
- How to get a part of string after a specified character in JavaScript?
- How to get the length of a string in JavaScript?
- Insert a specified element in a specified position in JavaScript?
- How to get the length of a string in bytes in JavaScript?
- Limiting numbers to a maximum value in MySQL?
- Generating random string with a specific length in JavaScript
- How to return a new string with a specified number of copies of an existing string with JavaScript?
- Padding a string with random lowercase alphabets to fill length in JavaScript
- Length of longest string chain in JavaScript
- Left pad a String with a specified String in Java
- Reversing the even length words of a string in JavaScript

Advertisements