Javascript Regex - ignoring specific characters between two characters

I need to split the string into a space character (''), but excluding any spaces that are included in 2 specific characters (e.g. single quotes).

Here is an example line:

This is the first token. This is a ----------- token. This is the third token.

The output array should look like this:

[0] = This-is-first-token
[1] = This-is-second-token
[2] = 'This is third token'

Question: Can this be done elegantly with regular expression?

+4
source share
3 answers

Short answer:

A simple regular expression for this purpose would be the following:

/'[^']+'|[^\s]+/g

Code example:

data = "This-is-first-token This-is-second-token 'This is third token'";
data.match(/'[^']+'|[^\s]+/g);

Result:

["This-is-first-token", "This-is-second-token", "'This is third token'"]

Explanation:

Regular expression visualization

Demo version of Debuggex

I think it is as simple as you can do it only in regular expression.

g , . .

\s ( , ). , , This-is-first-token This-is-second-token .

, :

data.match(/\{[^\}]+\}|[^\s]+/g);

Regular expression visualization

Debuggex

:

data.match(/\{[^\}]+\}|'[^']+'|[^\s]+/g);

Regular expression visualization

Debuggex

+9

:

var string = "This-is-first-token This-is-second-token 'This is third token'";
var arr = string.split(/(?=(?:(?:[^']*'){2})*[^']*$)\s+/);
//=> ["This-is-first-token", "This-is-second-token", "'This is third token'"]

, .

+1

I came up with the following:

"This-is-first-token This-is-second-token 'This is third token'".match(/('[A-Za-z\s^-]+'|[A-Za-z\-]+)/g)
["This-is-first-token", "This-is-second-token", "'This is third token'"]
0
source

All Articles