Jetson John
Jetson John

Reputation: 3829

How do I split this string using JavaScript?

I have this string

(<<b>>+<<10>>)*<<c>>-(<<x>>+<<y>>) 

Using JavaScript, what is the fastest way to parse this into

[b, 10, c, x, y]

Upvotes: 3

Views: 124

Answers (4)

poke
poke

Reputation: 387567

var str = '(<<b>>+<<10>>)*<<c>>-(<<x>>+<<y>>) ';
var arr = str.match(/<<(.*?)>>/g);
// arr will be ['<<b>>', '<<10>>', '<<c>>', '<<x>>', '<<y>>']

arr = arr.map(function (x) { return x.substring(2, x.length - 2); });
// arr will be ['b', '10', 'c', 'x', 'y']

Or you can also use exec to get the capture groups directly:

var regex = /<<(.*?)>>/g;
var match;
while ((match = regex.exec(str))) {
    console.log(match[1]);
}

This regular expression has the benefit that you can use anything in the string, including other alphanumerical characters, without having them matched automatically. Only those tokens in << >> are matched.

Upvotes: 3

David Thomas
David Thomas

Reputation: 253308

I'd suggest:

"(<<b>>+<<10>>)*<<c>>-(<<x>>+<<y>>)".match(/[a-z0-9]+/g);
// ["b", "10", "c", "x", "y"]

JS Fiddle demo.

References:

Upvotes: 5

Lonely
Lonely

Reputation: 613

use regex

var pattern=/[a-zA-Z0-9]+/g
your_string.match(pattern).

Upvotes: 3

CD..
CD..

Reputation: 74096

Try this:

'(<<b>>+<<10>>)*<<c>>-(<<x>>+<<y>>)'.match(/[^(<+>)*-]+/g)

Upvotes: 5

Related Questions