Home > Blockchain >  Take key values from a string in Javascript
Take key values from a string in Javascript

Time:09-28

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.

CodePudding user response:

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

  • Related