1

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.

2
  • Show your code! Handling escaped quotes inside a regex shouldn't be a problem (basically you let it contain a repeated sequence of almost anything ending in an escaped quote) Commented Apr 3, 2021 at 13:40
  • @StefanHaustein but how can i retain the information of whether if i am in the quote or not in regex? Commented Apr 3, 2021 at 14:15

2 Answers 2

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

5 Comments

This was the approach I tried, though it fails on 'apple"banana"hello"world"'' and 'apple "banana" hello" world"'
@ReturnCos In the example inside the question you did not mention any single quotation. please update the question respectively. also add other examples of what the input should be and what the output should be. that would help with determining what you really want to achieve.
i don't need the single quotations. I just put them to represent the string. Just ignore them.
@ReturnCos i updated the answer, as i tested it, it gets banana and hello, world on both cases you mentioned. check it out.
fails on apple "banana" hello" world"dasd"asdfasds"

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.