The Wayback Machine - https://web.archive.org/web/20241127032327/https://www.geeksforgeeks.org/javascript-program-to-remove-last-character-from-the-string/
Open In App

JavaScript Program to Remove Last Character from the String

Last Updated : 17 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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:

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

Approach 5: Using Regular Expression

The regular expression approach uses replace() with a regex pattern targeting the last character (.$) and replacing it with an empty string. This effectively removes the last character from the string, providing a concise solution.

JavaScript
function removeLastCharacter(str) {
    return str.replace(/.$/, '');
}
const input1 = 'Geeks for geeks';
const output1 = removeLastCharacter(input1);
console.log(output1); 

const input2 = 'Geeksforgeeks';
const output2 = removeLastCharacter(input2);
console.log(output2);

Output
Geeks for geek
Geeksforgeek

Approach 6: Using Array.from() Method

In this approach, we will convert the string into an array using the Array.from() method. This method creates a new array from an array-like or iterable object. Once the string is converted to an array, we can use the pop() method to remove the last character and then convert the array back to a string using the join() method.

Example: This method provides a straightforward way to remove the last character by leveraging the flexibility of arrays and their built-in methods

JavaScript
function removeCharacter(str) {
    let arr = Array.from(str);
    arr.pop();
    return arr.join('');
}

let str = "Geeksforgeeks";
console.log(removeCharacter(str)); 

// Output
// Geeksforgeek

Output
Geeksforgeek






Similar Reads

How to Find the First and Last Character of a String in JavaScript ?
We are going to learn about finding the first and last character of a string in JavaScript. The first character of a string is its initial symbol, while the last character is the final symbol at the end of the string. Strings are sequences of characters. Here we have some common methods to find the first and last character of a string by using Java
5 min read
JavaScript- Remove Last Characters from JS String
These are the following ways to remove first and last characters from a String: 1. Using String slice() MethodThe slice() method returns a part of a string by specifying the start and end indices. To remove the last character, we slice the string from the start (index 0) to the second-to-last character. [GFGTABS] JavaScript let str = "Hello GF
2 min read
How to remove portion of a string after certain character in JavaScript ?
Given a URL and the task is to remove a portion of URL after a certain character using JavaScript. split() method: This method is used to split a string into an array of substrings, and returns the new array. Syntax:string.split(separator, limit)Parameters:separator: It is optional parameter. It specifies the character, or the regular expression, t
3 min read
Remove a Character From String in JavaScript
We are given a string and the task is to remove a character from the given string. The replace() method can be used to replace or remove the specific character from the given string. Using replace() - Removes First OccurrenceWe replace "G" with "" using replace() method [GFGTABS] JavaScript let s = "GeeksForGeeks"; res = s.replace("G
2 min read
JavaScript - Remove all Occurrences of a Character in JS String
These are the following ways to remove all occurrence of a character from a given string: 1. Using Regular ExpressionUsing a regular expression, we create a pattern to match all occurrences of a specific character in a string and replace them with an empty string, effectively removing that character. [GFGTABS] JavaScript let str = "Geeks-for-G
2 min read
How to get the last character of a string in PHP ?
In this article, we will find the last character of a string in PHP. The last character can be found using the following methods. Using array() Method: In this method, we will find the length of the string, then print the value of (length-1). For example, if the string is "Akshit" Its length is 6, in zero-indexing, the value of (length-1) is 5 whic
2 min read
How to replace characters except last with the specified mask character in JavaScript ?
In this article, we have given a number and the task is to replace the characters except for the last character with a specified mask character in JavaScript. These are the following methods: Using Naive approachUsing slice() and replace methodUsing reduce() methodExample: Let's take a number 12345678 and the masking character is * and the number o
4 min read
How to Remove First and Last Element from Array using JavaScript?
Removing the first and last elements from an array is a common operation. This can be useful in various scenarios, such as data processing, filtering, or manipulation. Example: Input: [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]Output: [ 2, 3, 4, 5, 6, 7, 8, 9 ]Removing first and last element in array can be done using below approaches: Table of Content Using
2 min read
JavaScript Program to Find the Index of the Last Occurrence of a Substring in a String
Finding the index of the last occurrence of a substring in a string is a common task in JavaScript. The last occurrence of a substring in a string in JavaScript refers to finding the final position where a specified substring appears within a given string. We may want to know the position of the last occurrence of a specific substring within a give
5 min read
Last-child and last-of-type selector in SASS
SASS is also called Syntactically Awesome Stylesheet. It is a programming language that is interpreted into CSS. The Last Child selector is a selector that allows the user to target the last element inside the containing element. This selector is also known as a Structural Pseudo class which means it is used for styling content on the basis of pare
2 min read
How to remove the first character of string in PHP?
Remove the very first character of a given string in PHP Examples: Input : GeeksforgeeksOutput : eeksforgeeksInput :, Hello geek!Output : Hello geek!Explanation: In PHP to remove characters from the beginning we can use ltrim but in that, we have to define what we want to remove from a string i.e. removing characters are to be known. Example: [GFGT
3 min read
How to Remove Special Character from String in PHP?
We are given a string and the task is to remove special characters from string str in PHP. Below are the approaches to remove special characters from string in PHP: Table of Content Using str_replace() MethodUsing str_ireplace() MethodUsing preg_replace() MethodUsing str_replace() MethodThe str_replace() method is used to remove all the special cha
2 min read
Javascript Program for Queries for rotation and Kth character of the given string in constant time
Given a string str, the task is to perform the following type of queries on the given string: (1, K): Left rotate the string by K characters.(2, K): Print the Kth character of the string. Examples: Input: str = "abcdefgh", q[][] = {{1, 2}, {2, 2}, {1, 4}, {2, 7}} Output: d e Query 1: str = "cdefghab" Query 2: 2nd character is d Query 3: str = "ghab
2 min read
JavaScript Program to Get a Non-Repeating Character From the Given String
In JavaScript, we can find the non-repeating character from the input string by identifying the characters that occur only once in the string. There are several approaches in JavaScript to get a non-repeating character from the given string which are as follows: Table of Content Using indexOf and lastIndexOf methodsUsing Set and Array.from()Using M
3 min read
JavaScript Program to Check if a String Contains any Special Character
This article will demonstrate the methods to write a JavaScript Program to check if a String contains any special characters. Any string that contains any character other than alphanumeric and space includes the special character. These special characters are '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '+', '=', '{', '}', '[', ']', '
5 min read
JavaScript Program to Count the Occurrences of a Specific Character in a String
In this article, we will see how to count the frequency of a specific character in a string with JavaScript. Counting the frequency of a specific character in a string is a common task in JavaScript. Example: Input : S = “geeksforgeeks” and c = ‘e’Output : 4Explanation: ‘e’ appears four times in str.Input : S = “abccdefgaa” and c = ‘a’Output : 3Exp
3 min read
JavaScript Program to Find K’th Non-Repeating Character in String
The K'th non-repeating character in a string is found by iterating through the string length and counting how many times each character has appeared. When any character is found that appears only once and it is the K'th unique character encountered, it is returned as the result. This operation helps identify the K'th non-repeating character in the
7 min read
JavaScript Program to Test if Kth Character is Digit in String
Testing if the Kth character in a string is a digit in JavaScript involves checking the character at the specified index and determining if it is a numeric digit. Examples:Input : test_str = ‘geeks9geeks’, K = 5 Output : True Explanation : 5th idx element is 9, a digit, hence True.Input : test_str = ‘geeks9geeks’, K = 4 Output : False Explanation :
5 min read
JavaScript Program to Find i’th Index Character in a Binary String Obtained After n Iterations
Given a decimal number m, convert it into a binary string and apply n iterations. In each iteration, 0 becomes “01” and 1 becomes “10”. Find the (based on indexing) index character in the string after the nth iteration. Input: m = 5, n = 2, i = 3Output: 1Input: m = 3, n = 3, i = 6Output: 1Approach 1Convert a decimal number into its binary represent
6 min read
JavaScript Program to Remove Vowels from a String
The task is to write a JavaScript program that takes a string as input and returns the same string with all vowels removed. This means any occurrence of 'a', 'e', 'i', 'o', 'u' (both uppercase and lowercase) should be eliminated from the string. Given a string, remove the vowels from the string and print the string without vowels. Examples: Input :
2 min read
JavaScript Program to Remove Non-Alphanumeric Characters from a String
We will see how to remove non-alphanumeric characters from a string in JavaScript. Non-alphanumeric characters are symbols, punctuation, and whitespace. Removing them from a string This task can be useful when you want to clean up user inputs, sanitize strings, or perform various text processing operations. There are multiple approaches to removing
4 min read
JavaScript Program to Remove Consecutive Duplicate Characters From a String
We are going to implement a JavaScript program to remove consecutive duplicate characters from a string. In this program, we will eliminate all the consecutive occurrences of the same character from a string. Example: Input: string: "geeks" Output: "geks"Explanation :consecutive "e" should be removedTable of Content Using Iterative LoopUsing Regula
5 min read
Javascript Program To Remove Duplicates From A Given String
Write a javascript program for a given string S which may contain lowercase and uppercase characters. The task is to remove all duplicate characters from the string and find the resultant string. Note: The order of remaining characters in the output should be the same as in the original string.Example: Input: Str = geeksforgeeksOutput: geksforExpla
3 min read
How to get value of a string after last slash in JavaScript?
The task is to get the string after a specific character('/'). Here are a few of the most used techniques discussed. We are going to use JavaScript. Below are the approaches used to get the value of a string after the last slash in JavaScript: Table of Content Approach 1: Using .split() method and .length propertyApproach 2: Using .lastIndexOf(str)
2 min read
How to Get the Last N Characters of a String in JavaScript
We will learn how to get the last N characters of a string in JavaScript. We have given a string and we need to get the "n" character from the last of the string. There are various methods for finding the "n" character from the last of the string. Below are the following methods through which we get the last N characters of a string in JavaScript:
3 min read
How To Get The Last Caracter of a String in JavaScript?
Here are the various approaches to get the last character of a String using JavaScript. 1. Using charAt() Method (Most Common)The charAt() method retrieves the character at a specified index in a string. To get the last character, you pass the index str.length - 1. [GFGTABS] JavaScript const s = "JavaScript"; const lChar = s.charAt(s.leng
3 min read
PHP program to find the length of the last word in string
We are given a string. We are required to write a program in PHP to find the length of the last word in the string using inbuilt functions. We have already discussed approach of solving this problem here. This article discusses the PHP solution to the problem. Examples: Input : "php exercises" Output : 9 Input : "geeks for geeks" Output : 5 We will
2 min read
JavaScript Program to find the Index of Last Occurrence of Target Element in Sorted Array
In this article, we will see the JavaScript program to get the last occurrence of a number in a sorted array. We have the following methods to get the last occurrence of a given number in the sorted array. Methods to Find the Index of the Last Occurrence of the Target Element in the Sorted ArrayUsing Linear Search(Brute Force method)Using Linear Se
4 min read
JavaScript Program to Check if Two Numbers have Same Last Digit
In this article, we will discuss how to check if two numbers have the same last digit in JavaScript. Checking the last digit of a number is a common requirement in programming tasks, and it can be useful in various scenarios. We will explore an approach using JavaScript to accomplish this task. Methods to Check Both Numbers have the Same Last Digit
4 min read
JavaScript Program to Interchange Elements of First & Last in a Matrix Across Columns
We are given a matrix and we have to interchange the elements of the first and last columns with each other in a matrix. Example: Input 1 : 1 1 5 0 2 3 7 2 8 9 1 3 6 7 8 2Output 1 : 0 1 5 1 2 3 7 2 3 9 1 8 2 7 8 6Table of Content Using the swapping logicUsing forEach methodUsing the swapping logicIn this method, we Iterate through each column of th
3 min read
three90RightbarBannerImg