3

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?

2
  • shouldn't the result be ['a','c a','c a','c ac 1234 abc'] ? Commented Feb 22, 2017 at 8:42
  • @marvel308 sorry! Why the result should be ['a','c a','c a','c ac 1234 abc']? I want result is ['a','c a','c a','c a','c 1234 abc']. I want to split ac too. Commented Feb 22, 2017 at 8:45

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

0

You could use a positive look ahead.

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

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

4 Comments

Thanks! But if str = "b1c a12c a23c ac 1234 abc", the result is wrong.
@Guo, please add the wanted result as well.
I wanted result is ['b1c a','c a','c a','c 1234 abc'], in fact, reslut is ['b','c a','c a','c a','c 1234 abc']
@Guo question how b1c a got parse to "b", "c a"?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.