简体   繁体   中英

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.

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

Try this:

function getStringInQuotes(text) {

    const regex = const regex = /(?<=")\w+ .*(?=")|(?<=")\w+(?=")|\"\w+\"(?=")|(?<=" )\w+(?=")|(?<=")\w+(?= ")/g

    return text.match(regex);

}

const text = `apple banana "pear" strawberries "\"tomato\"" "i am running out of fruit\" names here"`;

console.log(getStringInQuotes(text));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM