1

I need to remove fractional addresses from a street address input line. I need to allow for people who enter strings like the following:

  • 1600 1/2 Main St
  • 1600 3/4 Main Street
  • 1600.5 Main St
  • 1600.75 3rd Street

The above examples should be output as follows:

  • 1600 Main St
  • 1600 Main Street
  • 1600 Main St
  • 1600 3rd Street

Here's what I've started with:

var ele = document.getElementById('billing_address_1');

if (typeof(ele) != 'undefined' && ele != null) {
    function fractionalAddress() {
        originalStreet = ele.value;

        //https://stackoverflow.com/questions/4328500/how-can-i-strip-all-punctuation-from-a-string-in-javascript-using-regex
        //var punctuationless = originalStreet.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g,"");
        //var finalStreet = punctuationless.replace(/\s{2,}/g," ");

        finalStreet = originalStreet.replace(/\s.*\//, '');          

        ele.value = finalStreet;
        console.log(originalStreet);
        console.log(finalStreet);
    };

    ele.addEventListener("change", fractionalAddress);
}

I haven't quite figured out how to grab the character after the slash but before the space. So, the above converts "1600 3/4 Main Street" into "16004 Main Street." Close, but not quite there!

What am I missing? Would it be better to split this into an array?

paulmiller3000
  • 436
  • 8
  • 24

2 Answers2

5

This works for me with the help of regex101.com

var addresses = `1600 1/2 Main St
1600 3/4 Main Street
1600.5 Main St
1600.75 3rd Street`

console.log(
addresses.replace(/ ?\d\/\d?|\.\d{1,}/g,"")
)

breakdown:

enter image description here

mplungjan
  • 169,008
  • 28
  • 173
  • 236
1

This regex seems to work.

finalStreet = originalStreet.replace(/\s*(\d+\/\d+|\.\d+)\s/g, '');   

A tip for the future, you can use a site like regex101.com to test and edit your regex

Toine H
  • 262
  • 2
  • 12