Reputation: 69
I'm trying to convert simple string which is nothing but xml data format into key/value pair.
input :-> str ='<name>xyz</name>'
output :-> {name : 'xyz'}
below are the myFunction but it's not showing exact outcomes
let str = '<name>xyz</name>'
function myFunction(str) {
let map ={}
let key
let value
str = str.split(/[.:;?!~,`"&|()<>{}[\]\r\n/\\]+/)
str = _.compact(str)
key = ??
value = ??
return map
}
Basically anything inside <> would be key and between closing tag would be output.I'm lacking proper logic here. Any help would be appreciable :-)
Upvotes: 0
Views: 1201
Reputation: 371009
Match whatever's between the first <
to >
to match the key, and match whatever's between the first >
and second <
to the value, then make an object out of it:
const str = '<name>xyz</name>';
const [,key,val] = str.match(/<([^>]+)>([^<]+)</);
const obj = { [key]: val };
console.log(obj);
Upvotes: 1