In JavaScript, you can use the `substring` method to get the first N characters from a string.
In this example,
str
with a string value of "Hello World"
.substring
method with str
, 0
as the start index, and 5
as the end index to get the first 5 characters.let str = "Hello World";
let first5Chars = str.substring(0, 5);
console.log(`First 5 characters of the string are: ${first5Chars}`);
First 5 characters of the string are: Hello
In this example,
str
with a string value of "apple"
.substring
method with str
, 0
as the start index, and 3
as the end index to get the first 3 characters.let str = "apple";
let first3Chars = str.substring(0, 3);
console.log(`First 3 characters of the string are: ${first3Chars}`);
First 3 characters of the string are: app
In this tutorial, we learned How to get First N Characters in String in JavaScript language with well detailed examples.