Here, in this article we will learn how to get the first 10 character from any string using JavaScript. Here we will be using JavaScript's String method substring.
The substring()
method in javascript extracts characters between two parameters from a given string and then return its substring.
The substring methods extracts the characters between the first param(start) and second param(last), but does not include the last.
Syntax:
string.substring(start, end)
Start
: the first position from where the extraction begins. The first position is at index 0.
end
: it up to (but not including) where the extraction ends.
To extract the first 10 character from a string, the syntax will be string.substring(0,10).
let str = "abcdefghijkl"
let tenChar = str.substring(0,10)
console.log(tenChar)
//abcdefghij <- FIRST 10 CHARACTER FROM THE STRING
The extraction of the character starts with the position 0 (the position is index 0 ) and ends with 10 (the position is index 9).
Note:
substring()
will swap the two arguments. Example (5,1) will be swap to (1,5).substring()
method will not bring as changes to the original string.