Search code examples
javascriptstringsplittokenize

Tokenize string with space separated values unless values are wrapped in single quotes


can any body tell me to split a string in java script with space which is not within single quote.

Like if string is

"0 60 120 180 'node name' 2 34 45 12"

then it will tokenize such that

arr[0]=0
arr[1]=60
arr[2]=120
arr[3]=180
arr[4]='node name'
arr[5]=2
arr[6]=34
arr[7]=45
arr[8]=12

During split if single quotes remove then also good as this is the legend name in chart and I have to fetch that name in single element


Solution

  • This regex will do it:

    var arr = string.match(/'[^']*'|[^ ]+/g) || [];