How to get the first three characters of a string using JavaScript ?
Last Updated :
03 Jan, 2024
In this article, we are going to learn how to get the first three characters of a string using JavaScript.
Example:
Input: today
Output: tod
Input: tomorrow
Output: tom
These are the approaches by which we can get the first three characters of a string using JavaScript:
The string.slice() is an inbuilt method in javascript that is used to return a part or slice of the given input string.
Syntax:
string.slice(startingIndex, endingIndex);
Example: In this example, we are using Slice() method.
Javascript
let originalString = "HelloWorld" ;
let firstThreeChars = originalString.slice(0, 3);
console.log(firstThreeChars);
|
Syntax:
let temp = str.substr(0, 3);
Example: In this example, we are using string.substr() method.
Javascript
let originalString = "Geeksforgeeks" ;
let firstThreeChars = originalString.substr(0, 3);
console.log(firstThreeChars);
|
Approach 3: Using For loop
JavaScript for loop is used to iterate the elements for a fixed number of times. JavaScript for loop is used if the number of the iteration is known.
Syntax:
for (statement 1 ; statement 2 ; statement 3){
code here...
}
Example: In this example, we are using For loop.
Javascript
let originalString = "HelloWorld" ;
let firstThreeChars = "" ;
for (let i = 0; i < 3; i++) {
firstThreeChars += originalString[i];
}
console.log(firstThreeChars);
|
JavaScript string.substring() is an inbuilt function in JavaScript that is used to return the part of the given string from the start index to the end index. Indexing starts from zero (0).
Syntax:
string.substring(Startindex, Endindex);
Example: In this example, we are using string.substring() method.
Javascript
let str = "HelloWorld" ;
let result = str.substring(0, 3);
console.log(result)
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...