簡體   English   中英

在 javascript 中獲取引號中的字符串

[英]Getting string in quotes in javascript

如何編寫 function 以從字符串中獲取引號中的所有字符串? 該字符串可能包含轉義引號。 我已經嘗試過正則表達式,但由於正則表達式沒有 state 之類的功能,我無法做到這一點。 例子:

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

應該返回一個數組,如['pear', '"tomato"', 'i am running out of fruit" names here']

也許有 split 的東西可以工作,雖然我不知道怎么做。

我使用以下 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;
}

嘗試這個:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM