jQuery serialize converts all spaces to plus

Mark Steggles picture Mark Steggles · Jun 14, 2012 · Viewed 12.4k times · Source

Currently, everywhere I use serialize I have to use it like this:

.serialize().replace(/\+/g,'%20');

otherwise any spaces in the form data will be coverted to +'s. Is there a setting that can make this the default.

Answer

russianmario picture russianmario · Apr 28, 2015

For fun, here's an alternative that doesn't use a temporary variable:

$.fn.serializeAndEncode = function() {
    return $.map(this.serializeArray(), function(val) {
        return [val.name, encodeURIComponent(val.value)].join('=');
    }).join('&');
};

$("#formToSerialize").serializeAndEncode();