How to usestring.substr() method in Javascript

Syntax: 

let temp = str.substr(0, 3); 

Example: In this example, we are using string.substr() method.

Javascript
let originalString = "w3wiki";
let firstThreeChars = originalString.substr(0, 3);
console.log(firstThreeChars);

Output
Gee

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

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:

Table of Content

  • Approach 1: Using Slice() method
  • Approach 2: Using string.substr() method
  • Approach 3: Using For loop
  • Approach 4: Using string.substring() method
  • Approach 5: Using Array.from(), slice(), and join() methods

Similar Reads

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....

Approach 2: Using string.substr() method

Syntax:...

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....

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

Approach 5: Using Array.from(), slice(), and join() methods

The Array.from() method creates a new array from an array-like or iterable object. In this case, it will convert the string into an array of characters. We can then use the slice() method to get the first three elements of the array and join() to convert the array back into a string....