I have a command like this: add "first item" and subtract "third course", disregard "the final power".
How do I extract all the strings so it outputs an array: ["first item", "third course", "the final power"]
I have a command like this: add "first item" and subtract "third course", disregard "the final power".
How do I extract all the strings so it outputs an array: ["first item", "third course", "the final power"]
Try using a regex that matches quote
, text
, quote
, then remove the captured quotes using map
:
const string = 'add "first item" and subtract "third course", disregard "the final power".';
const quotes = string.match(/\"(.*?)\"/g).map(e => e.split("\"")[1]);
console.log(quotes);
One solution is to use a global regexp like this and just loop through
var extractValues = function(string) {
var regex = /"([^"]+)"/g;
var ret = [];
for (var result = regex.exec(string);
result != null;
result = regex.exec(string)) {
ret.push(result[1]);
}
return ret;
}
extractValues('add "first item" and subtract "third course", disregard "the final power".')
Note, however, that, most answers, including this one, does not deal with the fact that values may have a quote in them. So for example:
var str = 'This is "a \"quoted string\""';
If you have this in your dataset you will need to adapt some of the answers.
var str = 'add "first item" and subtract "third course", disregard "the final power".';
var res = str.match(/(?<=(['"])\b)(?:(?!\1|\\).|\\.)*(?=\1)/g);
console.log(res);
Reference : Casimir et Hippolyte's solution on Stackoverflow
You can use this
"[^"]+?" - Match "
followed by anything expect "
(one or more time lazy mode) followed by "
let str = `add "first item" and subtract "third course", disregard "the final power"`
let op = str.match(/"[^"]+?"/g).map(e=>e.replace(/\"/g, ''))
console.log(op)