Remove a Character From String in JavaScript
In this article, we are given a string and the task is to remove a character from the given string. We have many methods to remove a character from a string that is described below.
The replace() method replaces the first occurrence of a specified character/string with another character/string.
Syntax:
string.replace('characterToReplace', '');
Example: This example shows the above-explained approach
Javascript
function removeCharacter() {
let originalString = "GeeksForGeeks" ;
newString = originalString.replace( "G" , "" );
console.log(newString);
}
removeCharacter();
|
This method is used to remove all occurrences of a specified character or string from the input string, unlike the previous method, which removes only the first occurrence.
It uses a regular expression with the global property to select and remove every occurrence.
Syntax:
string.replace(/regExp/g, '');
Example: This example shows the above-explained approach
Javascript
function removeCharacter() {
originalString = "GeeksForGeeks" ;
newString = originalString.replace(/G/g, "" );
console.log(newString);
}
removeCharacter();
|
The slice() method is used to extract parts of a string between specified indices.
- When removing the first character, you specify the starting index as 1, which extracts the string from the second character to the end.
- To remove the last character, you specify the ending index as one less than the string’s length, extracting the string from the beginning to the second-to-last character.
Syntax:
string.slice(start, end)
Example: This example shows the above-explained approach
Javascript
function removeCharacter() {
originalString = "GeeksForGeeks" ;
firstCharRemoved = originalString.slice(1);
lastCharRemoved = originalString
.slice(0, originalString.length - 1);
console.log(firstCharRemoved);
console.log(lastCharRemoved);
}
removeCharacter();
|
Output
eeksForGeeks
GeeksForGeek
The substr() method is used to remove a character from a specific index within the string.
It extracts portions of a string between specified parameters and then joins the parts before and after the character to be removed.
Syntax:
string.substr(start, length)
Example: This example shows the above-explained approach
Javascript
function removeCharacter(position) {
originalString = "GeeksForGeeks" ;
newString =
originalString.substr(0, position - 1)+
originalString.substr(
position,
originalString.length
);
console.log(newString);
}
removeCharacter(6);
|
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
Last Updated :
28 Nov, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...