Get the 10 characters from a string using Javascript.


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.

What is substring() method in javascript?

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.

Extract first 10 characters from a String using JavaScript substring()

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:

  1. If the start position is greater then the end position, the substring() will swap the two arguments. Example (5,1) will be swap to (1,5).
  2. If the start or the end argument is less the 0, the will be treated as 0
  3. Thesubstring()method will not bring as changes to the original string.

💾 Recommended Articles