简体   繁体   中英

How to remove remaining commas from a string using JavaScript Regex?

I am trying to make a dynamic address builder to be used in combination with GMap Geocoder.

My code is like the following:

HTML

<input type="text" class="address" />
<input type="text" class="city" />
<input type="text" class="state" />
<input type="text" class="zipCode" />
<input type="text" class="country" />

JavaScript

$('.address, .city, .state, .zipCode, .country').blur(
    function()
    {
        var address = '';

        address += $('.address').val() + ', ';
        address += $('.city').val() + ', ';
        address += $('.state').val() + ', ';
        address += $('.zipCode').val() + ', ';
        address += $('.country').val();

        console.log(address);
    }
);

The problem now :

When I blur the address field I am getting the following in my console:

MyAddress, , , ,

also, in some case (at least for my area) there are two names for the same location and we use coma to separate them. In example the address can become something like that:

MyAddress, MySecondAddress, Cityname, State, zipCode, Country

The Question:

while the address is builded automatically, how can I remove the remaining commas from the address string by using regex?

One possible approach:

address = address.replace(/,(?:\s*,)+/g, ',').replace(/^,|,$/g, '');

But actually, I would probably do it a bit differently: collect all the non-empty values into an array, then join this array with ',':

var $addressFields = $('.address, .city, .state, .zipCode, .country');

$addressFields.blur(function() {
  var nonEmptyParts = $.map($addressFields, function(inp) {
    var inputStr = $.trim(inp.value);
    return inputStr === '' ? null : inputStr;
  });
  var fullAddress = nonEmptyParts.join(',');
  console.log(fullAddress);
});

I've employed a convenient feature of $.map here: when the callback function returns null (or undefined ), the value is not added to the resulting array.

You should correct the root of the problem instead of removing the extra commas. In the first place you should not add the commas in this way; as you can see it's adding commas even if the field is empty.

Please try something like this:

HTML:

<form id="myform">
    <input type="text" class="address" name="address" />
    <input type="text" class="city" name="city" />
    <input type="text" class="state" name="state" />
    <input type="text" class="zipCode" name="zipCode" />
    <input type="text" class="country" name="country" />
</form>

JS:

var address = [];

// no need for that long line of selectors
$("#myform > input").blur(function(e){
    if ($(this).val()) { // only add this field if it has a value
        address.push($(this).val());
    }
    console.log(address.join(', ')); // tada, no more extra commas
});

If your form has other inputs, use a div to group the inputs instead.

address = address.replace(/( ?,)+/, '');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM