>我有一个字符串变量,其值采用名称值对的格式,例如
firstname:"John", lastname:"Doe", age:50,eyecolor:"blue".
现在,如何从此字符串中获取值?
您可以创建一个 JSON 对象,然后访问对象的键以获取所需的值。
var tempObj = {};
var str = 'firstname:"John", lastname:"Doe", age:50,eyecolor:"blue"';
str.split(',').forEach((item)=>{
var key = item.split(':')[0].trim();
var value = item.split(':')[1].replace(/"/g,'').trim();
tempObj[key] = value;
});
console.log(tempObj);
console.log("First name is "+ tempObj.firstname);
对于 JavaScript,如果单个变量只包含一对,您可以使用split
const name = 'firstname:John';
const [prop, value] = name.split(':');
console.log(prop); //prints 'firstname'
console.log(value); //prints 'John'