user123123123 user123123123 - 1 year ago 86
Javascript Question

Regex split delimiters with content that has no whitespace

I'm trying to write a regular expression but I have encountered difficulties.

My goal is to split the contents within 2 delimiters with some conditions.

For example.

var str = "foo -word- a b -word2- a b-c -word3- h- b-";

The result of the split must be:

var result = [
"foo", "word", "a b",
"word2", "a b-c",
"word3", "h- b-"

For now I have done this:

var result = str.split(\-(.*?)-\);

But i want to capture only the delimiters that do not contain white space.

Answer Source

The problem is that you are using .* when you could be specifying a range or class of characters. Try this:

var result = str.split(-(\S+)-);

\S is any non-whitespace character, and this is looking for any one or more of them.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download