-2

I am a newbie on regular expression. Could anybody suggest a regex to split string like below using Javascript? The text I am dealing with should be split by a space character but sometimes it contains space within the text snippet like below:

Input: SST+CONF!001 001 "407968017" "Projector Serial Number"

Desired output: ['SST+CONF!001', '001', '407968017', 'Projector Serial Number']

Please help!

Thank you!

Wayne Ohm
  • 61
  • 1
  • Possible duplicate of [How to split on white spaces not between quotes?](https://stackoverflow.com/questions/40479546/how-to-split-on-white-spaces-not-between-quotes) – BAHRI Abdelhak Jan 17 '19 at 10:20
  • thanks. The following did the trick. var tokens = line.match(/(?!^)".*?"/g); – Wayne Ohm Jan 18 '19 at 00:53

2 Answers2

1

This is longer than a one liner regex, but it converts the input to the format of the desired output you are looking for using split and regex:

var yourstring = 'SST+CONF!001 001 "407968017" "Projector Serial Number"';

// Regex to replace " with '
yourstring = yourstring.replace (/"/g,"'");

// Split where " " is 
strArray = yourstring.split(" ");

var output = "[";

for (var i = 0; i < strArray.length; i++) {
  if(i < 2){
    strArray[i] = "'" + strArray[i] + "'";
  }
  if (i < 3){
    output += strArray[i] + ", ";
  }
  else {
    output += strArray[i] + " ";
  }
}

// Regex to replace last character with ]
output = output.replace(/.$/, "]");

console.log(output);

Hope it helps!

hiew1
  • 1,394
  • 2
  • 15
  • 23
0

Use the split function and use the regex provided inside it. It splits the array based on the regex. The regex finds all the space in the string

var a='SST+CONF!001 001 407968017 Projector Serial Number';
var b=a.split(/\s/g)
console.log(b)
ellipsis
  • 12,049
  • 2
  • 17
  • 33