Open In App

How to get the first three characters of a string using JavaScript ?

Improve
Improve
Like Article
Like
Save
Share
Report

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:

Approach 1: Using Slice() method

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);


Output

Hel

Approach 2: Using string.substr() method

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);


Output

Gee

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); // Output: Hel


Output

Hel

Approach 4: Using string.substring() method

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)


Output

Hel


Last Updated : 03 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads