[英]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 ? 我一直在尝试对json键值对使用trim()
,但是似乎无法正常工作,请任何人帮忙吗?
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]
: 将调整后的值分配给特定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. 另外,如果您不能使用.trim()
因为老的浏览器中,使用填充工具为。
function trim(string) {
return string.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
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: 那是因为您无法访问JSON
值,例如:
var value = json[key]; // Wrong
You must do it like this: 您必须这样做:
var value = json.key; // Correct
All browsers since IE9+ have trim() 自IE9 +起的所有浏览器都具有trim()
For those browsers who does not support trim(), you can use this polyfill from MDN: 对于不支持trim()的浏览器,可以使用MDN中的以下polyfill:
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, '');
};
})();
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.