简体   繁体   中英

remove whitespace inside json object key value pair

I have been trying to use trim() for json key value pair , but it seems not to work, can anyone please help ?

var user = { first_name: "CSS",
  last_name: "  H ",
  age: 41,
  website: "java2s.com"
};

for (var key in user) {
  console.log((key+"-->"+user[key].trim());
}

Assign the trimmed value to the specific user[key] :

 var user = { first_name: "CSS", last_name: " H ", age: 41, website: "java2s.com" }; for (var key in user) { user[key] = user[key].toString().trim() console.log(key+"-->"+user[key]); } 

Also, if you cannot use .trim() because of older browsers, use a polyfill for that.

Recommended:

function trim(string) {
    return string.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};

Evil edition:

if (!String.prototype.trim) {
    String.prototype.trim = function () {
        return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
    };
}

That's because you can't access a JSON value like:

var value = json[key]; // Wrong

You must do it like this:

var value = json.key; // Correct

All browsers since IE9+ have trim()

For those browsers who does not support trim(), you can use this polyfill from MDN:

if (!String.prototype.trim) {
(function() {
    // Make sure we trim BOM and NBSP
    var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
    String.prototype.trim = function() {
        return this.replace(rtrim, '');
    };
})();

}

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