Keep Only First N Characters in a JavaScript String

For JavaScript programming, you might want to grab just a part containing the first N characters from a string. This comes in especially handy while reducing the long text in case of creating a preview or formatting user input.
Here’s how one can keep only the first N characters in a JavaScript string. With code examples, we shall discuss the necessary tasks in an orderly way.
1. Using substring()
The substring() function hunts on a string for the desired characters that lie in the range between two declared indexes.
Example:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Keep First N Characters</title>
</head>
<body>
<script>
let str = "Hello, JavaScript!";
let firstN = str.substring(0, 5);
console.log(firstN); // Output: "Hello"
</script>
</body>
</html>

 

2. Using slice()
The slice() method also extracts the substring of a string, much like substring(), but it supports negative indices as well.
Example:

<script>
let str = "Hello, JavaScript!";
let firstN = str.slice(0, 5);
console.log(firstN); // Output: "Hello"
</script>

 

3. Using substr() (Deprecated but still in use)
An example of the substr() function would be to take a part of a string, that is, a particular number of characters from a string, with consideration to the starting index. Please, notice that it is not favorable to use it, and it is only for new browsers.

Example:

<script>
let str = "Hello, JavaScript!";
let firstN = str.substr(0, 5);
console.log(firstN); // Output: "Hello"
</script>

 

4. Using String Prototype with Custom Function
You could write a function that will allow you to take away the first N characters from any string you pass as an argument.

Example:

<script>
function getFirstNCharacters(str, n) {
return str.length > n ? str.substring(0, n) : str;
}
let text = "Learning JavaScript is fun!";
console.log(getFirstNCharacters(text, 8)); // Output: "Learning"
</script>

 

5. Handling Edge Cases
It is important to handle the cases in which the string is shorter than the length of N.
Example:

<script>
let shortStr = "I";
console.log(getFirstNCharacters(shortStr, 5)); // Output: "I"
</script>

 

Conclusion
There are many ways of selecting only the first N characters of a JavaScript string:
substring() which is a direct and simple way for this purpose.
slice() to get the substring as per the user’s requirements.
substr() this method is not used anymore but it is still working so one can use another.

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top