Skip to content Skip to sidebar Skip to footer

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',

Solution 1:

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('-'));

Solution 2:

You could use a positive look ahead.

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

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

Post a Comment for "How To Split String In Javascript Using Regexp?"