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
  • 43,180
  • 11
  • 50
  • 79
Harry
  • 52,711
  • 71
  • 177
  • 261

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
  • 43,180
  • 11
  • 50
  • 79
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
  • 370
  • 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,966
  • 1
  • 18
  • 34
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
  • 37,143
  • 5
  • 39
  • 60