Split text into words ignoring the single quoted word in text in JavaScript

Muh*_*fiq 0 javascript arrays string typescript

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"]
Run Code Online (Sandbox Code Playgroud)

Any help will be appreciated.

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

Krz*_*ski 6

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

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

console.log(str.match(/('.*?'|[^\s]+)/g));
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

41 次

最近记录:

4 年,6 月 前