Parsing a templated string

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Parsing a templated string



So I have a string like this


const str = 'map("a")to("b");map("foo")to("bar");map("alpha")to("beta");'



I wanted to parse this string to generate a json something like


[id: 'a', map: 'b',
id: 'foo', map: 'bar',
id: 'alpha', map: 'beta']



I was wondering if regex is the best way to do this or if theres any utility lib I could leverage




2 Answers
2



Here's a regex that should work for your current case:




const str = 'map("a")to("b");map("foo")to("bar");map("alpha")to("beta");';

const res = str.split(";").map(e =>
const k = e.match(/map("(.+?)")to("(.+?)")/);
return k && k.length === 3 ? id: k[1], map: k[2] : null;
).filter(e => e);

console.log(res);



The idea is to split on semicolons (a lookaround could be used to handle cases when semicolons are part of your desired key/value), then map these pairs into the desired object format based on a regex that parses the map("")to("") format.


map


map("")to("")



I'm pretty sure there is a nice regex solution which is shorter and faster, but since i'm bad at regex i solve those things like that:


const str = 'map("a")to("b");map("foo")to("bar");map("alpha")to("beta");'

const result = str.split(';').map(e =>

const parts = e.substring(3).split('to').map(item => item.replace(/W/g, ''));

return
id: parts[0],
map: parts[1]
;
)
console.log(result);





Just have to slice off the last element in the split...otherwise result[3] is id: "", map: undefined
– thmsdnnr
1 min ago


id: "", map: undefined






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

Creating a leaderboard in HTML/JS