0

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.

enter image description here

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.

P.S : this quoted words could be repeated in text many time in any position.

Muhammad Shafiq
  • 129
  • 1
  • 9

1 Answers1

6

I recommend using regex, in the example below the first part of the regex matches anything between the quotes and the 2nd part of the regex matches anything but spaces

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

console.log(str.match(/('.*?'|[^\s]+)/g));
Krzysztof Krzeszewski
  • 5,912
  • 2
  • 17
  • 30