sukkis sukkis - 4 months ago 8
Javascript Question

How to javascript match exactly 7 numbers from different urls

I have URL addresses like



My javascript bookmarklet looks something like below.

javascript:(function(){javascript:var location_pathname = document.location.href;var ggId = location_pathname.match(/^[0-9]{7}$/)[1]; window.open('http://localhost/script.php?id='+ggId, '_blank')})()


How to match those 7 numbers from each urls? Above is my script but it does not work. If I match example with
"/\/something\/(.*)/"
code works and opens new tab http://localhost/script.php?id=9303033 but it works only in some cases.

Answer

If there are exactly 7 digits after slash (/) and another slash or EOL then correct RegEx is

var re = /\/(\d{7})\/?|$/; //note (\d{7}) This is what will be captured
//tests
'http://www.gg.omg/whatever/4303013'.match(re)[1]; //4303013
'http://www.gg.omg/whatever/4303013/maybe'.match(re)[1]; //4303013
'http://www.gg.omg/whatever/430301'.match(re)[1]; //undefined