charlieroth
charlieroth

Reputation: 33

Javascript String Splitting

So if I have a string like:

'boss: "Person 1" AND occupation: "Engineer"'

Is there a way I can split the string into an array like such:

['boss:', '"Person 1"', 'AND', 'occupation:', '"Engineer"']

I have lots of different regex splits and multiple argument splits and I can't seem to achieve this. Any ideas?

FYI: yes I would like to leave in the quotations surrounding Person 1 and Engineer and maintain the spaces in whatever is between quotations

Thanks!

Upvotes: 0

Views: 52

Answers (2)

Valdi_Bo
Valdi_Bo

Reputation: 30971

If console.log prints an array, it surrounds each string element with apostrophes, so you see the apostrophes only in console output.

If you want to get a string formatted the way you want, use the following script:

var str = 'boss: "Person 1" AND occupation: "Engineer"';
var pat = /"[^"]+"|\S+/g;
var res1 = str.match(pat);
var result = "['" + res1.join("', '") + "']";

Upvotes: 0

user94559
user94559

Reputation: 60143

var input = 'boss: "Person 1" AND occupation: "Engineer"';

console.log(input.match(/"[^"]*"|[^ ]+/g));

// Output:
// [ 'boss:', '"Person 1"', 'AND', 'occupation:', '"Engineer"' ]

Explanation

You want to match two kinds of things:

  1. Things without spaces in them (since spaces separate terms).
  2. Things in quotes (where spaces are allowed).

The regular expression here consists of two parts:

  1. "[^"]*" - This matches a double quote, followed by any number of non-double-quote characters, followed by another double quote.
  2. [^ ]+ - This matches one or more non-space characters.

The two are combined with a pipe (|), which means "or." Together, they match both types of things you want to find.

Upvotes: 1

Related Questions