1

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"]

Jack Bashford
  • 40,575
  • 10
  • 44
  • 74
Harry
  • 49,643
  • 70
  • 169
  • 251

4 Answers4

2

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);
Jack Bashford
  • 40,575
  • 10
  • 44
  • 74
1

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.

Marcio Lucca
  • 360
  • 2
  • 10
0
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

Şivā SankĂr
  • 1,856
  • 1
  • 16
  • 32
0

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)
Code Maniac
  • 35,187
  • 4
  • 31
  • 54