0

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!

1
  • 1
    what have you tried? where are you stuck? Commented Jun 28, 2017 at 19:31

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Another answer here pointed out that the first part of the regular expression could be ".*?" instead. I think that's perfectly fine too.
0

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("', '") + "']";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.