In this tutorial post, let’s look at the different ways to remove a character from a string. We’ll be looking and multiple ways of removing a character, but also solutions to multiple problem statements within this problem as well.
To start with, let’s look at removing every instance of a given character from a string. Then let’s look at removing characters from a given position, or a first instance of a character and so on.
We’ll be looking at 3 different ways of doing the same as well.
Remove a character using the string replace function
One of the easiest ways to remove a character from a string is by using the replace function, a pre-defined function in Javascript.
All we need to do here is replace the character we want removed with an empty string. I’ll show you how.
var a = "Hellllooo there!"; a = a.replace("l",""); document.write(a);
You’ll get the following output:
So, what happened here is, the replace function scanned the string “a” and when it encountered the first “l”, it replaced that character with an empty string. So now, the word “Hellllooo” became “Helllooo”.
This function works great if you just want to remove the first instance of that character from the string.
Remove every occurrence of the character using regular expressions
But what if you want to remove every instance of that character from the string? Globally remove a character from the string, I mean.
This is where regular expressions come in. With regular expressions, you can specify certain conditions to facilitate the character replace.
Now, the above function, if written with a regular expression will be written as follows:
a = a.replace(/l/,"");
If I replace the above line of code in the original code snippet, I’ll still get the same output. The first instance of “l” is removed.
Now, I can add a condition to this regular expression, a global condition that basically instructs the browser to remove every instance of “l” from the above string.
a = a.replace(/l/g,"");
All I need to do is add a “g” to the regular expression, which is code for “global” and I’ll get the following output:
Notice how every instance of the character “l” has been removed from the string.
Doing this might seem redundant in this case, but what if a string has junk characters that need removed? Then this syntax will come in handy. I’ll show you how.
var str = "Hel&&lo&&& there!"; str = str.replace(/&/g,""); document.write(str);
In the above example, the string “str” has a bunch of junk characters “&”.
I’ve tried to remove all of them by using the String replace function with regular expressions, and a global condition.
This is what I’ll get in the output:
Every occurrence of the junk character “&” has been removed and we are left with the string “Hello there!”, as it should have originally been.
So now you see how the global condition can be helpful.
Remove character from a given position
Using the slice function
If you noticed above, you can’t really remove characters from a given position with the replace function. It either removes the first instance of the character it finds or all instances of the character (if you use the global condition with a regular expression).
What if you want to remove the 5th character in a string, for example?
In order to do that, you’ll need the slice() function. I’ll show you how that works now.
var str = "Hell&o there!";
So, let’s define a string where the character we need removed is in the 5th position.
But the thing with strings is, the characters of a string can be accessed from 0, not 1.
For instance, str[0] will access the character “H”, str[1] will access the character “e” and so on.
So, the character we want removed, “&” is actually in position 4 as far as Javascript and your browser is concerned.
So what we’re going to do here is slice the string from position 0 to 4 (which would give us the substring “Hell”) and slice the string again from position 5 to the end of the string (which would give us the substring “o there!”) and concatenate both of these substrings together to get our required output. Then, reassign the new string to the original variable “str” to reflect the change.
Let me show the same in code:
var str = "Hell&o there!"; str = str.slice(0,4) + str.slice(5,str.length); document.write(str);
When I run the above program, I’ll get the following output:
Notice how we used str.length to calculate the length of the string. This will save us manual calculation, or another line of code where we calculate the length and apply the value to the slice.
Also, as you can see, the slice function usually slices the string from the first given position to the last position-1.
So, slice(0,4) actually takes the substring from position 0 to 3, and not 4. It would omit out the last position 4. So, if I want 4 removed, I’d need to include it in the first slice, and not include it in the 2nd slice function.
Similarly, notice how the 2nd slice function specifies str.length at the end, even though str[str.length] would have no character in it. That’s because this slice function would only take the characters str[5] through str[str.length-1] in to account.
So, whenever we know the position of the character that needs removed, we can use the slice function just like above and remove it from the string.
Using the substring or substr functions
You can achieve the same result as above by using substring() and substr() functions as well. Let me show you examples of both.
The slice() and substring() functions work the same way. They both consider characters from the first given position to the second given position – 1.
So, without further ado, let me show you an example using the substring() function.
var str = "Hell&o there!"; str = str.substring(0,4) + str.substring(5,str.length); document.write(str);
As you can see. The above code snippet works the same way the one with the slice() function did. There is not much to explain.
That’s how the substr() function works as well.
var str = "Hell&o there!"; str = str.substr(0,4) + str.substr(5,str.length); document.write(str);
So far, we’ve written the code knowing where the character we want removed is positioned. What if you don’t know?
If you’d like to get user input to determine the position, then you’ll need to use user-defined functions.
So, let’s try to use one of these methods with a function, shall we?
So, to start off, I’m going to create a function and name it removeChar. This function is going to receive two parameters, str and pos.
function removeChar(str, pos) {
Str stands for the string and pos stands for the position of the character you want removed. So, everything is unknown in this program until the function gets a function call.
Then, inside the function, I’m going to create a standard formula using substr(). You can also use the substring() and slice() functions and achieve the same result.
We’re going to take the “pos” value, and create substrings from the character in the 0th position to just before the character in the “pos” position so that character is excluded, and create another substring from the very next character to the rest of the string (by using the str.length property).
This will ensure that we exclude the character in the “pos” position (by giving the value as pos+1) and get the remaining.
str = str.substr(0,pos) + str.substr(pos+1, str.length);
Then, let’s return the string so it gets displayed on the output screen.
return str;
Now, all you need to do is create a function call that lists the string and the position of the character you want removed and display it on the screen. You can do this in multiple ways.
If you use the document.write property, you’ll get the same output as the one you got in the previous section.
document.write(removeChar("Hello@ there!", 5));
But you can also use the alert property to achieve the same result. In fact, it’s recommended to use either the alert property or one of the DOM properties to manipulate a HTML element in your webpage because document.write is clunky at the best of times. I just use it to quickly show you how things works.
So if I use the alert function, this is what I get:
alert(removeChar("Hello@ there!", 5));
So far, we’ve assumed that the user calculates the position of a given character the way Javascript or your browser calculates it – by starting the first position with 0.
But that’s not how we do things in the real world. In the real world, the first character is in position 1, the second character is in position 2, the last character is in position str.length (not str.length – 1), and so on.
So, if we take the user understanding into account, we’ll need to change our code accordingly. Let me show you how:
function removeChar(str, pos) { str = str.substr(0,pos-1) + str.substr(pos, str.length); return str; } alert(removeChar("Hello@ there!", 6));
In the above code snippet, we’ve given the position as 6, since the character we want removed, which is “@”, is in the 6th position in the string (Considering “H” is in the 1st position).
So, we’ve changed the formula accordingly because even though humans count from 1, your browser is always going to start with 0.
The first substring takes the characters in positions 0 to pos-2 (since the character in position pos-1 will be excluded by the substr() function) and the second substring takes the characters in positions pos to str.length-1 (since str.length is excluded), and we get the required result.
So, this is how you create a more user-friendly program. You can’t always expect your users to know how browsers think, so you need to do the background work for them.
Using split and Join
This isn’t the best way to achieve want we want. We’re going to be using the split() function in Javascript to split the string into different parts and create an array out of it based on a given “split” factor. Then, we’re going to join the two split strings with an empty string as the “join” factor.
This might seem a bit confusing when I explain it in words, so let me show you an example.
var str = "Hello% World!";
I’ve created a string “str” and as you can see above, the character we want removed is “%”.
Now, let’s use the split() function:
str = str.split("%");
So, I’ve used the split function and given “%” as the common denominator for the split and assigned the newly formed array (with 2 items inside of it) back to the “str” variable.
document.write(str + "<br/>");
When I display “str”, this is what I get.
As you can see from the above screenshot, the string is split into two, and “Hello” and “World!” are now the 2 elements of the array “str”.
Now, I’m going to join this array back, with an empty string as the common denominator to get the string we wanted.
str = str.join(""); document.write(str);
The result would be the original string without the unwanted character “%” in it.
Now you see why we used an empty string and not another character to merge the string.
What if the same character is present more than once in the string? Let’s see what happens.
var str = "Hello% Wor%ld!"; str = str.split("%"); document.write(str + "<br/>");
In the above example, we are splitting the string into an array with 3 different elements, as shown below:
Then, when we join the different parts back into a string, this is what we get:
str = str.join(""); document.write(str);
So, as you can see, we are removing every instance of the character when we use the split function.
The above method works best if you already know the character you want removed. What if you want to send these details dynamically?
You can create a function to achieve that as well. Let me quickly show you how:
function removeChar(str, char) { str = str.split(char).join(""); return str; } document.write(removeChar("Hello% World!", "%"));
In the above function, instead of sending the position of the character we want removed, we are sending the actual character we want removed.
Manual method of removing a character from a string
Ok, we’ve looked at a couple of pre-defined functions that can be used to remove a given character from a string. Is there a manual way of doing the same? Of course, there is, and you show know how to do it because that’s how you learn a language.
We’re going to create a function for this code snippet as well. The function removeChar is going to accept 2 parameters – str and char. Str will contain the original string and char will contain the character you want removed from the string.
function removeChar(str, char) {
Then, let’s create another variable called “newStr” and assign it an empty string to start with. This string is going to contain the desired string at the end of the loop we’ll be creating.
var newStr = "";
Next, let’s create a for loop that loops through the string.
for(var i=0; i<str.length; i++) {
As it loops through every character in the string, whenever the particular character it encounters is not equal to the “char” value sent by the function call, let’s append that to the end of the newStr string.
By doing this, the for loop will skip over the character that we want removed and add the remaining characters and spaces, so we’ll end up with the string we need.
if(str[i] !== char) { newStr += str[i]; } }
Let’s return the string to the function call so it can be printed.
return newStr; } document.write(removeChar("Hello* World!", "*"));
When we run the above program, this is the output we end up with:
As you can see, the code snippet works. Let me paste the entire snippet so you can use it if you want to:
function removeChar(str, char) { var newStr = ""; for(var i=0; i<str.length; i++) { if(str[i] !== char) { newStr += str[i]; } } return newStr; } document.write(removeChar("Hello* World!", "*"));
That’s it! We’ve looked at 6 different ways to remove a character from a string in Javascript.
I wanted to cover every method I can think of, but if you want to write a well-optimized code, stick to the method with the lowest run time and the least number of codes.
Function calls with either the slice(), substr() or substring() functions will work great.