Guo
Guo

Reputation: 1803

how to split string in javascript using RegExp?

There is a string:

var str = "a1c a12c a23c ac 1234 abc";

and a RegExp:

var re = /a(\d*)c/g;

I want to split str by number that between a and c, the result I want is:

['a','c a','c a','c a','c 1234 abc']

how to do it?

Upvotes: 3

Views: 101

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386560

You could use a positive look ahead.

var str = "a1c a12c a23c ac 1234 abc";

console.log(str.split(/\d*(?=\d*c.*a)/));

Upvotes: 0

John Bupit
John Bupit

Reputation: 10618

One way is to replace numbers with a special character ('-' in this case), and split with that character.

str.replace(/a(\d*)c/g, 'a-c').split('-');

var str = "a1c a12c a23c ac 1234 abc";
var re = /a(\d*)c/g;

console.log(str.replace(re, 'a-c').split('-'));

Upvotes: 3

Related Questions