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

5
  • 4
    what you have tried? Commented Feb 2, 2019 at 2:04
  • Use a regular expression that matches a double quotes, a sequence of non-double quote characters, and another double quote. Commented Feb 2, 2019 at 2:06
  • str.split(/[\w\s,]+(\s|,)"|"./).filter(w => w && w.trim()) Commented Feb 2, 2019 at 2:21
  • Interesting and tricky question :) Please find the solution below which may be answer for your question. Commented Feb 2, 2019 at 2:48
  • Possible duplicate of RegEx: Grabbing values between quotation marks Commented Feb 2, 2019 at 3:43

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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)

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.