2

I have MMYY pattern ( credit card expiry)

I need to analyze each section (01 and 14) : So I tried :

'0114'.split(/\d{2}/i) //  ["", "", ""]

It actually see 2 digits as a separators and hence I get nothing.

However , I've managed to do it with :

'0114'.match(/\d{2}/ig) //["01", "14"]

But I wonder about split.

Can I do it also with split ?

0

3 Answers 3

9

For example:

"1234".split(/(?=..$)/) => ["12", "34"]

A generic solution for strings of arbitrary length appears to be impossible, the best we can get is something like:

str.split(str.length & 1 ? /(?=(?:..)*.$)/ : /(?=(?:..)+$)/)
Sign up to request clarification or add additional context in comments.

4 Comments

positive lookahead of _____ ?
positive look ahead include the char itself ? I mean (changed a bit to test) "1234".split(/(?=..)/i) yield ["1", "2", "34"] . why do i get also 34 ?
@RoyiNamir: lookarounds match "between" characters, two dots without $ match in two places: 1^2^34.
what about "123456" ? why it doesnt split the string to 12,34,56 ?
3

This should do it:

   '0114'.split(/(?=..$)/)

Comments

1

No reason to use regex - I'd simply use substring:

var str = '0114';
var month = str.substr(0, 2);
var year = str.substr(2, 2);
console.log(month, year); // 01 14

1 Comment

Thanks for the laugh, but I, for one, can appreciate @h2ooooooo's alternative solution. :)

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.