Regex tricks – Change strings to formatted numbers

(regex == regular expressions)

There are a few Regex tricks that I use constantly in my javascript stuff to control numbers or variable names. Here are a few examples of Regex in action.

Remove non-numeric characters except periods:

This will take a string or number and change it to an integer or a float that you can do math with. It will take something like 18,500 and turn it into 18500 (or 18,500.24 to 18500.24) – This can also strip $ dollar signs.

//Removes any non-numeric characters except for periods. 
//strips dollar signs $ and commas ,
.replace(/[^\d.]/g,'')

//Here I use it to get sq_ft to float for a variable
//parseFloat # value after stripping the string of 
//special characters except period (.)
var totalsqft = parseFloat($("#square_feet").val().replace(/[^\d\.]/g,''));

Change to fixed number with two decimals:

.toFixed(2) can change something like 18.3445 to 18.34 .toFixed(0) can get you an integer if need be –

//changes to fixed number with two decimals
.toFixed(2)

//here I use it to:
//make sure your number is fixed number with no decimal places
var totalsqftfixed = totalsqft.toFixed(0);

Add commas to a number:

//adds commas
.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")

//make sure commas are correct with decimal
var sqftformatted = sqftfixed.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");

Here is a function that utilizes all of those methods:

This is a javascript function to take a number that came from the db such as 18500 and make it formatted as you want to see it in the input field on the form. So this one will make 18500 look like 18,500 – This function runs anytime anyone messes with the input field and on page load.

//format total area square feet input for Area
    function formatTotalAreaSquareFeet()
    {
        //parseFloat # value after stripping the string of special characters except period (.)
        var totalsqft = parseFloat($("#area_area_square_feet").val().replace(/[^\d\.]/g,''));
        //if totalbaserent doesn't exist, make it zero
        if (!totalsqft){
            totalsqft = 0;
        }
        //make sure your float is fixed number with no decimal places
        var totalsqftfixed = totalsqft.toFixed(0);
        //make sure commas are correct
        var totalsqftformatted = totalsqftfixed.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
        //change # to total
        $("#area_area_square_feet").val(totalsqftformatted);
        //this input field is saved as a string
    }
    
    //change or keyup on # will trigger function
    $(document).on("change, keyup, blur", "#area_area_square_feet", formatTotalAreaSquareFeet);
    //make it happen onload
    $(document).ready(formatTotalAreaSquareFeet);

I move on later on these forms to strip out the commas for submit to database. (It could also strip dollar signs if needed). So this is taking that 18,500 or 18,500.24 from above and making it the way you need it to match your input field. Here it is simple square feet saved as an integer.

//Function to format for Submit to Database
    function formatForSubmitAreaSquareFeet()
    {
        //parseFloat # value after stripping the string of special characters except period (.)
        var totalsqft = parseFloat($("#area_area_square_feet").val().replace(/[^\d\.]/g,''));
        //if totalbaserent doesn't exist, make it zero
        if (!totalsqft){
            totalsqft = 0;
        }
        //make sure your float is fixed number with no decimal places
        var totalsqftfixed = totalsqft.toFixed(0);
        //change # to total
        $("#area_area_square_feet").val(totalsqftfixed);
        //this input field is saved as a string
    }

    //Before Submit Run Function(s)
    $('.formatFunctions').submit(function() {
      //Runs Function to strip special characters except (.)
      formatForSubmitAreaSquareFeet();
    });