Removing space between serialize() text

I am trying to remove space from my serialized object, as US and UK code has spaces. My syntax is as following, but i am getting error wit spaces not being stripped.
var str = $( “form” ).serialize();
var res = $(str).replace(/ /g,‘’);

The serialize method url encodes the serialized string, so all the spaces get replaced with the + symbol. That’s why your regex isn’t working.

what is the workaround that? @fretburner

Can I ask why you’re trying to remove the spaces? Is it that you’re trying to remove trailing spaces from your form inputs or something like that?

@fretburner so, i got this code, and as per postal code, it has spaces in it. Like AB 7DC. The value will be serialized as AB+7DC, whereas my zipfinder API accepts no spaces or special charachters, so i need to make this AB7DC

OK, so if it’s just a single input that we’re talking about, I wouldn’t bother with serialize(). You can just grab the value directly and replace the spaces:

var postcode = $('#postcode').val().replace(/ /g,'');

@fretburner In example i illustrated one example, what happen is, i have a form, in which one address street and zip code. It connects to a ajax calls, send over the parameter and get the result pay to display.

In that case, what you can do is use jQuery’s serializeArray():

var formValues = $(form).serializeArray(),
    data = {};

formValues.forEach(function(el) {
    data[] = ( === 'postcode') ? el.value.replace(/ /g, '') : el.value;

The method returns an array of objects containing name/value properties for each form control. You can then loop over this array and assign them to an empty object. As you loop over the array, you can check the name property - if it matches your postcode field then remove the spaces, otherwise just copy the value as-is. Now you’re left with a data object that you can pass to one of jQuery’s AJAX methods.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.