Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How can I cut a string after X characters in JavaScript?
To cut a string after X characters in JavaScript, you can use several methods. The most common approaches are substr(), substring(), and slice().
Using substr() Method
The substr() method extracts a portion of a string, starting at a specified index and extending for a given number of characters.
var myName = "JohnSmithMITUS";
console.log("The String = " + myName);
var afterXCharacter = myName.substr(0, 9);
console.log("After cutting the characters the string = " + afterXCharacter);
The String = JohnSmithMITUS After cutting the characters the string = JohnSmith
Using substring() Method
The substring() method extracts characters between two specified indices.
var text = "JavaScript Programming";
console.log("Original string: " + text);
var cutString = text.substring(0, 10);
console.log("Cut after 10 characters: " + cutString);
Original string: JavaScript Programming Cut after 10 characters: JavaScript
Using slice() Method
The slice() method extracts a section of a string and returns it as a new string.
var message = "Hello World Example";
console.log("Original: " + message);
var slicedString = message.slice(0, 11);
console.log("Sliced after 11 characters: " + slicedString);
Original: Hello World Example Sliced after 11 characters: Hello World
Adding Truncation Indicator
You can add an ellipsis (...) or other indicator to show the string was truncated.
var longText = "This is a very long string that needs to be truncated";
var maxLength = 20;
var truncated = longText.length > maxLength
? longText.substr(0, maxLength) + "..."
: longText;
console.log("Truncated: " + truncated);
Truncated: This is a very long ...
Comparison of Methods
| Method | Syntax | Negative Values | Status |
|---|---|---|---|
substr() |
substr(start, length) | Allowed | Deprecated |
substring() |
substring(start, end) | Treated as 0 | Recommended |
slice() |
slice(start, end) | Counts from end | Recommended |
Conclusion
While substr() works, it's deprecated. Use substring() or slice() for modern JavaScript development. Both methods effectively cut strings after X characters.
Advertisements
