我有一个字符串变量,其值的格式为名称值对,如
firstname:"John", lastname:"Doe", age:50,eyecolor:"blue".
现在,我怎样才能从这个字符串中获取值?
答案 0 :(得分:1)
您可以创建一个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);

答案 1 :(得分:0)
对于javascript,如果单个变量只包含一对,则可以使用split
const name = 'firstname:John';
const [prop, value] = name.split(':');
console.log(prop); //prints 'firstname'
console.log(value); //prints 'John'