parsings strings: extracting words and phrases [JavaScript]

前端 未结 10 668
没有蜡笔的小新
没有蜡笔的小新 2020-12-01 19:20

I need to support exact phrases (enclosed in quotes) in an otherwise space-separated list of terms. Thus splitting the respective string by the space-character is not suffic

10条回答
  •  春和景丽
    2020-12-01 19:38

    ES6 solution supporting:

    • Split by space except for inside quotes
    • Removing quotes but not for backslash escaped quotes
    • Escaped quote become quote

    Code:

    input.match(/\\?.|^$/g).reduce((p, c) => {
            if(c === '"'){
                p.quote ^= 1;
            }else if(!p.quote && c === ' '){
                p.a.push('');
            }else{
                p.a[p.a.length-1] += c.replace(/\\(.)/,"$1");
            }
            return  p;
        }, {a: ['']}).a
    

    Output:

    [ 'foo', 'bar', 'lorem ipsum', 'baz' ]
    

提交回复
热议问题