Remove Comma From String – Building a JavaScript Application

Table of Contents

In this post we are going to go over various ways we can use JS to remove either one or many commas from a string. We are also going to build a custom JavaScript application where we utilize some of these techniques. You can find the application towards the bottom of the post. If you want to check out other web development guides then have a look in the right hand side column.

You can also see see the techniques taught here used in this JavaScript Text Scanner Project.

TL;DR: (There are more options later in the post)

var purpose = "I, Just, want, a, quick, answer!";

// Removing the first occurrence of a comma
var result = purpose.replace(",", "");

// Removing all the commas
var result = purpose.replace(/,/g, "");

Different ways to remove one or more commas from a string

There are various ways to remove one or more commas from a string using JavaScript. We will look at 3 different ways. Two will use built in functions, and we will also have one example using our own function to do it.

1. Using the .replace() function to remove commas

The replace function is one of the easiest ways to replace something. It is a built in function so you should have no problem using it.

A) Using .replace() to remove a single comma in a string

var iAmAString = "Once upon a time, long long ago"; 
var iAmAlsoAString = iAmAString.replace(",", ""); 

console.log(iAmAlsoAString);

This code will take the comma and remove it. But that was just with one comma, what if we have several?

var iHaveManyCommans = "Once, upon, a, time, long, long, ago";
var howManyCommasDoIHave = iHaveManyCommans.replace(",", "");

console.log(howManyCommasDoIHave );

You can see the output from the above code in the image below.

Using remove() on a string with many commas

As you can see, using .replace(“,”, ”) only removes the first comma from the string. If you want to use JavaScript to remove all the commas from a string, then there is a simple regular expression flag that you can add to make it accomplish that.

B) Using .replace() to remove all the commas in a string

var iHaveManyCommans = "Once, upon, a, time, long, long, ago";
var howManyCommasDoIHave = iHaveManyCommans.replace(/,/g, '');

console.log(howManyCommasDoIHave );

Adding the g, “global”, will make it remove all the commas in your string. Going into regular expression is beyond the scope of this article, but you can use regular expression with the .replace() function for powerful string manipulation.

2. Using .split() and .join() to remove commas

There are a few other ways that we can remove commas from a string using JavaScript, and one of them is to use the .split() and .join() functions. This will remove all the commas.

var iHaveManyCommans = "Once, upon, a, time, long, long, ago";
var howManyCommasDoIHave = iHaveManyCommans.split(',').join("");

console.log(howManyCommasDoIHave);

This technique will first split the string on the commas. This will return an array of words. At this point you could loop over the array and do something if you wanted, or you can use the .join() function to join all the indices on whatever you give as input. If you wanted to have a dash in-between all the words you could use .join(“-“). If you give an empty string as we do above it will put it back together just without the commas. Since there was already a space in between the words it will still have the spaces.

3. Removing commas with a custom function

You can also remove commas by doing everything manually. By manually I mean to loop over all the characters of a string and removing the commas. Since a string is immutable in JavasScript we are actually creating a new string instead of removing them from the old value.

var testSentence = "hello, there, how are you doing?";

function removeSymbol(symbol, str){
    var newString = "";
    for(var i = 0; i < str.length; i++) {
        var char = str.charAt(i);
        if(char != symbol){
            newString = newString + char;
        }
    }
    return newString;
}

console.log(removeSymbol(",", testSentence));
// Prints "hello there how are you doing?"

In the solution above we iterate over each character in the string. If the character is not equal to the symbol we want to remove, then we add that symbol to the new string. At the very end we return the string without any of the symbols.

When might you use these techniques?

A common reason for using JavaScript to remove a comma from a string is if you have a number with a thousand separator, and you want to get rid of either one or many of them. Most times you will be given a number but it is in the form of a string, but it has the comma in it so you cant use it because it is seen as a string, it is difficult to convert it too because of the commas. Using the .replace() function is a good solution to this problem.

An example is:

Lets say you have an input box where you display the number with a thousand separator. The user inputs a number and you get the value. You now have a string that is lets say “1,200”. If you now want to do math with this value you first have to remove the comma from the string. There are a number of ways you can do this, and there are three listed in this post. Being able to remove a comma with JavaScript is quite useful.

Building a number counter that can deal with commas

To get a better understanding of how we might apply the techniques from this post to a real application, lets build a tool that will read in a list of numbers and add them together. This application will be able to remove commas from numbers so that it can actually use them for computation.

The functionality that will be central to this application is the ability to deal with numbers that have commas in them.

Lets start by creating the HTML elements that we need for this project.

1. HTML Elements

We need the following elements for our application.

  1. Input textarea – Where we can input a list of numbers
  2. A button to initiate our application
  3. A label where we can display the total
<textarea id="customInput">100 1,000 100,000 10 10,000</textarea>

<button id="initiate">Count</button>

<label id="total">The total will be placed here</total>

2. Adding a little styling to our HTML

We want to add just a little styling to make things look better. We want to make the button a block element and we want a little more room above and below the button. We also want to change the background color as it is white by default on this WordPress theme.

<style>
    #initiate{
        background-color: #bdd7ff; 
        margin: 20px 0px;
        display: block;
    }
</style>

3. Creating JavaScript logic

Our logic here will be to;

  1. first get the text from the text area.
  2. Then we want to turn that text into an array, where each word in the text is in one of the indexes.
  3. When we have the array we are going to loop over each of the words, removing all the commas in each word.
  4. After removing the comma we are going to turn it into a number and add it to our total. If it is not a number then we will not add it.

In essence this application should only take numbers as inputs, but since this is a text box there could potentially be some words depending on user input.

var button = document.getElementById("initiate"); 

button.addEventListener("click", function(){ 
    var total = process();
    document.getElementById("total").innerHTML = "The total is: " + total;
});

function process(){
    var total = 0;

    var text = getText();
    var array = text.split(" ");

    for(var i = 0; i < array.length; i++){
        var noComma = array[i].split(',').join("");
        console.log(noComma);
        if(!isNaN(noComma)){
            total += parseFloat(noComma);
        }
    }

    return total;
}

function getText(){
    return document.getElementById("customInput").value + '';
}

That is it for our JS logic. Below you will find the entire application embedded on the page so that you can try it out.

Working Application

Enter whole numbers separated by a space on this line. They can have thousand separator and the application will take care of them using the techniques from this post.

Related Guides