SplittextintowordsignoringthesinglequotedwordintextinJavaScript

I am trying to split text into words on the basis of space but I don't want to split words in single quotes into different words.

Here if you can see word 'fd f df' is converted into three words 'fd , f , df'
but I want to get this as single word like 'fd f df'.

const str = `TEST = 'fd f df' AND Pitch = 444`
str.split(/s+/)
// ["TEST", "=", "'fd", "f", "df'", "AND", "Pitch", "=", "444"]

Any help will be appreciated.

PS:这个引用的词可以在文本中的任何位置多次重复。

回答

我建议使用正则表达式,在下面的示例中,正则表达式的第一部分匹配引号之间的任何内容,正则表达式的第二部分匹配除空格之外的任何内容

const str = `TEST = 'fd f df' AND Pitch = 444`

console.log(str.match(/('.*?'|[^s]+)/g));


以上是SplittextintowordsignoringthesinglequotedwordintextinJavaScript的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>