Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Take key values from a string in Javascript

How would I take some key values from a string thats formatted like this and save each value into a variable?
[Alert] <value here> has thrown a <value here> in <value here>.
I’m really not sure how to go about this… Maybe regex? I’m not very familiar with regex.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The regex is pretty simple and can be almost identical to your string. Where you want to pick out some words use the match syntax (.+) – the period is "any character", and the + is "one or more".

Use match on the string with the expression to return an array of matches which you can then destructure into a number of variables (I’ve called them a b and c here).

// Note: you have to escape the `[` and `]` around "Alert"
// as they are part of regex syntax. `^` and `$`
// signify the start and end of the string respectively
const re = /^\[Alert\] (.+) has thrown a (.+) in (.+)\.$/;
const str = '[Alert] Trump has thrown a tantrum in his Evil Lair.'

const [full, a, b, c] = str.match(re);

console.log(a, b, c);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading