Th3Moron Th3Moron - 1 year ago 40
Javascript Question

JS Regex last two digits matches the first two digits

I'm new to regex, so please bare with my stupid question.

I've been trying to get this to work for a couple of hours now, and i still can't get i to work, as i want to.

What i need is, i have 4 number, and i need the last 2 numbers, to be the same as the first 2.

Like this would be a match:


This in the other hand, should not be a match:


I can't seem to get it to work, and i'm clueless on how to actually do it.

This is what i've got so far:


Can i get some help, moving on? or a finger point in the right direction, on how to do it, or where to look it up, so i can find the answer my self.

Thanks in advance


You can use


for 4 digit strings. See this regex demo.

var good_strs = ["1212", "1313", "1414"];
var bad_strs = ["1513", "1314", "1236"];
var res_good = => /^(\d{2})\1$/.test(x));
document.body.innerHTML = "Good string test:<pre>" + JSON.stringify(res_good, 0, 4) + "</pre>";
var res_bad = => /^(\d{2})\1$/.test(x));
document.body.innerHTML += "Bad string test:<pre>" + JSON.stringify(res_bad, 0, 4) + "</pre>";

If there can be any characters in between, just insert [\s\S]* in between:


See another regex demo (lazy matching used for demo only).