parsings strings: extracting words and phrases [JavaScript]

前端 未结 10 678
没有蜡笔的小新
没有蜡笔的小新 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:55

    var str = 'foo bar "lorem ipsum" baz';  
    var results = str.match(/("[^"]+"|[^"\s]+)/g);
    

    ... returns the array you're looking for.
    Note, however:

    • Bounding quotes are included, so can be removed with replace(/^"([^"]+)"$/,"$1") on the results.
    • Spaces between the quotes will stay intact. So, if there are three spaces between lorem and ipsum, they'll be in the result. You can fix this by running replace(/\s+/," ") on the results.
    • If there's no closing " after ipsum (i.e. an incorrectly-quoted phrase) you'll end up with: ['foo', 'bar', 'lorem', 'ipsum', 'baz']

提交回复
热议问题