Methods to keep only First N characters in a String

Table of Content

  • Using substring() Method
  • Using slice() Method
  • Using JavaScript For loop
  • Using String’s substr() Method


JavaScript to keep only first N characters in a string

In this article, we have given a string and the task is to keep only the first n characters of the string using JavaScript. There are various methods to solve this problem, some of which are discussed below: 

Similar Reads

Methods to keep only First N characters in a String:

Table of Content Using substring() MethodUsing slice() MethodUsing JavaScript For loopUsing String’s substr() Method...

Method 1: Using substring() Method

The string.substring() method is used to return the part of the given string from the start index to the end index. Indexing starts from zero (0)....

Method 2: Using slice() Method

The string.slice() method is used to return a part or slice of the given input string....

Method 3: Using JavaScript For loop

Looping in programming languages is a feature that facilitates the execution of a set of instructions repeatedly until some condition evaluates and becomes false. We come across for loop which provides a brief and systematic way of writing the loop structure....

Method 4: Using String’s substr() Method

The substr() method is used to extract parts of a string, beginning at the specified start position, and returns the specified number of characters....

Method 5: Using Array.prototype.join() with Array.from()

The Array.from() method creates a new, shallow-copied Array instance from an array-like or iterable object. By converting the string into an array of characters, we can easily manipulate and then join the desired portion back into a string....