Search code examples
javascriptparsingquotesliterals

Getting string in quotes in javascript


How may I write a function to get all the strings in quotes from a string? The string may contain escaped quotes. I've tried regex but as regex does not have a state like feature, I wasn't able to do that. Example:

apple banana "pear" strawberries "\"tomato\"" "i am running out of fruit\" names here"

should return an array like ['pear', '"tomato"', 'i am running out of fruit" names here']

Maybe something with split can work, though I can't figure out how.


Solution

  • I solved this problem using the following function:

    const getStringInQuotes = (text) => {
    
        let quoteTogether = "";
        let retval = [];
        let a = text.split('"');
        let inQuote = false;
        for (let i = 0; i < a.length; i++) {
            if (inQuote) {
                quoteTogether += a[i];
                if (quoteTogether[quoteTogether.length - 1] !== '\\') {
                    inQuote = false;
                    retval.push(quoteTogether);
                    quoteTogether = "";
                } else {
                    quoteTogether = quoteTogether.slice(0, -1) + '"'
                }
            } else {
                inQuote = true;
            }
        }
        return retval;
    }