Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split JS string via Regex?

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 ?

like image 430
Royi Namir Avatar asked Jul 04 '26 08:07

Royi Namir


1 Answers

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 ? /(?=(?:..)*.$)/ : /(?=(?:..)+$)/)
like image 162
georg Avatar answered Jul 07 '26 01:07

georg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!