Open In App

JavaScript Program to Remove Last Character from the String

Last Updated : 31 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn how to remove the last character from the string in JavaScript. The string is used to represent the sequence of characters. Now, we will remove the last character from this string.

Example:

Input : Geeks for geeks
Output : Geeks for geek
Input : Geeksforgeeks
Output : Geeksforgeek

Below are the following approaches through which we can remove the last character from the string:

  • Using for loop
  • Using the slice() Method
  • Using substring() Method
  • Using split() and join() Method

Approach 1: Using for loop

In this approach, we will use a brute force approach for removing the character from the string. We run the loop through the string and iterate over all the characters except the last character. Now, return the modified string.

Example:

Javascript




function removeCharacter(str) {
    let n = str.length;
    let newString = "";
    for (let i = 0; i < n - 1; i++) {
        newString += str[i];
    }
    return newString;
}
  
let str = "Geeksforgeeks";
console.log(removeCharacter(str));


Output

Geeksforgeek

Approach 2: Using the slice() Method

In this approach, we will slice method for removing the last character of the string.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:

Javascript




function removeCharacter(str) {
    let newString = str.slice(0, -1);
    return newString;
  
}
let str = "Geeksforgeeks";
console.log(removeCharacter(str));


Output

Geeksforgeek

Approach 3: Using substring() Method

In this approach, we will use substring() method for removing last character of string. The 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 start from zero (0). 

Syntax: 

string.substring( Startindex, Endindex )

Example:

Javascript




function removeCharacter(str) {
    let newString = str.substring(0, str.length - 1);
    return newString;
  
}
let str = "Geeksforgeeks";
console.log(removeCharacter(str));


Output

Geeksforgeek

Approach 4: Using split() and join() Method

In this approach, we will split the string and then we use pop() method for removing the last character and then we will use join() method for joining the array back.

Example:

Javascript




function removeCharacter(str) {
    let splitString = str.split('')
    splitString.pop();
    return splitString.join('');
  
}
let str = "Geeksforgeeks";
console.log(removeCharacter(str));


Output

Geeksforgeek


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads