0

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 :-)

1 Answer 1

1

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);

Sign up to request clarification or add additional context in comments.

1 Comment

Huh, es6 computed property names...how had I missed that until now?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.