最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - remove whitespace inside json object key value pair - Stack Overflow

matteradmin7PV0评论

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"
};

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

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."
};

for (var key in user) {
  console.log((key+"-->"+user[key].trim());
}
Share Improve this question edited Jun 21, 2018 at 15:13 Eazy 16813 bronze badges asked Jun 21, 2018 at 14:51 NinjaDevNinjaDev 3011 gold badge8 silver badges19 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

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

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

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.

Remended:

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, '');
    };
}

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, '');
    };
})();

}

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
Post a comment

comment list (0)

  1. No comments so far