Open In App

JavaScript to keep only first N characters in a string

Last Updated : 23 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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: 

Methods to keep only First N characters in a String:


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

Syntax:

string.substring(Startindex, Endindex)

Example: This example uses the above-explained approach.

javascript
// JavaScript to keep only first
// 'n' characters of String

// Original string
let str = "GeeksforGeeks";

// Keep first 5 letters
let n = 5;

console.log("Original String = " + str);
console.log("n = " + n);

// Using substring() method
str = str.substring(0, n);

console.log("Keep first " + n +
    " characters of original String = " + str);

Output
Original String = GeeksforGeeks
n = 5
Keep first 5 characters of original String = Geeks

Method 2: Using slice() Method

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

Syntax:

string.slice(startingindex, endingindex)

Example: This example uses slice() method to get part of a string.

javascript
// JavaScript script to keep only
// first 'n' characters of String

// Original string
let str = "Data Structure";

// Keep first 11 letters
let n = 11;

console.log("Original String = " + str);
console.log("n = " + n);

// Using slice() method
str = str.slice(0, n);

console.log("Keep first " + n +
    " characters of original String = " + str);

Output
Original String = Data Structure
n = 11
Keep first 11 characters of original String = Data Struct

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. 

Syntax:

for (statement 1 ; statement 2 ; statement 3){
code here...
}

Example: In this example, we will loop till the given index and store characters in the result string.

Javascript
// JavaScript to keep only first
// 'n' characters of String

// Original string
let str = "GeeksforGeeks";

// Keep first 5 letters
let n = 5;
let res = "";
console.log("Original String = " + str);
console.log("n = " + n);

// Loop till given number of characters
for (let i = 0; i < n; i++) {
    res += str[i];
}

console.log(
    "Keep first " + n +
    " characters of original String = "
    + res
);

Output
Original String = GeeksforGeeks
n = 5
Keep first 5 characters of original String = Geeks

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.

Syntax:

string.substr(startIndex, length)

Example:

JavaScript
// JavaScript to keep only first
// 'n' characters of String

// Original string
let str = "Hello World";

// Keep first 5 characters
let n = 5;

console.log("Original String = " + str);
console.log("n = " + n);

// Using substr() method
str = str.substr(0, n);

console.log("Keep first " + n +
    " characters of original String = " + str);

Output
Original String = Hello World
n = 5
Keep first 5 characters of original String = Hello




Similar Reads

JavaScript/TypeScript: Standard way to keep the cause of an Error
In this article, we will try to understand that what's the standard way to keep the cause of an Error in JavaScript (or in TypeScript) with the help of certain coding examples. Since there is no such provision provided in JavaScript/TypeScript where directly we may be able to find out the cause of an error (like no such property or in-built method
2 min read
JavaScript Program to Check if a String Contains only Alphabetic Characters
In this article, we are going to learn about checking if a string contains only alphabetic characters in JavaScript.Checking if a string contains only alphabetic characters means verifying that all characters within the string are letters of the alphabet (A-Z or a-z) and do not include any digits, symbols, or other non-alphabetic characters. Some c
3 min read
JavaScript Program for Min flips of continuous characters to make all characters same in a String
In this article, we will learn about Min flips of continuous characters to make all characters the same in a string using JavaScript. Min flips of continuous characters in a string refer to the minimum number of changes required to turn a sequence of adjacent characters into a uniform sequence, ensuring all characters are the same. Given a string c
3 min read
JavaScript Program to Remove First and Last Characters from a String
This article will show you how to remove the first and last characters from a given string in JavaScript. There are two methods to remove the first and last characters in a string. Using String slice() MethodUsing String substring() MethodUsing String slice() MethodThe string.slice() method returns a part or slice of the given input string. Syntax:
2 min read
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: todayOutput: todInput: tomorrowOutput: tomThese are the approaches by which we can get the first three characters of a string using JavaScript: Table of Content Approach 1: Using Slice() methodApproach 2: Using string.substr()
2 min read
HTTP headers | Keep-Alive
The Keep-Alive header is a general-type header. This header is used to hint at how the connection may be used to set a timeout and a maximum amount of requests. It can also be used to allow a single TCP connection to remain open for multiple HTTP requests/responses (default HTTP connection closed after each request). It is also known as a persisten
2 min read
How to keep compiled files in a separate directory ?
A web project containing HTML, CSS, JavaScript, Images, and Videos files. The task is to ensure that all the files of the project are compiled and bundled to one separate directly. Before we proceed, I would like to give you a brief introduction to parcel-bundler. Parcel-bundler: It is a module that helps to transcribe our ES6+ syntax into a tradit
4 min read
Best approach for “Keep Me Logged In” using PHP
We all have noticed the "Keep Me Logged In" checkbox in most of the websites we log in to. There are different ways and approaches to achieve this through code. The best approach among those is saving the User information in the user browser as cookies. Basically, we have to store both the Username and the Password in the user's browser as cookies.
2 min read
Underscore.js _.keep() Method
The _.keep() method takes an array and a function and hence returns an array generated which keeps only true values based on the conditions of the function. Syntax: _.keep(array, function) Parameters: array: The given array from which the keep array is created.function: The function containing the conditions for elements to be kept. Return Value: T
2 min read
Lodash _.keep() Method
The Lodash _.keep() method takes an array and a function and hence returns an array generated which keeps only true values based on the conditions of the function. Syntax: _.keep( array, function ) Parameters: This method takes two parameters as mentioned above and described below: array: The given array from which keep array is created.function: T
2 min read