0

i have a current page url that looks like this:

http://localhost/admin/namespace_module/yeezy/index/test_id/5/key/23123asda/

the url can be dynamic but always contain /test_id/value/ , first i want to check if the /test_id/ is exist in my current url:

window.location.href

then i need to retrieve the value

Idham Choudry
  • 559
  • 8
  • 27

3 Answers3

1

Use RegExp#test method.

if(/\/test_id\//.test(window.location.href)){

}

or use String#indexOf method.

if(window.location.href.indexOf('/test_id/') > -1){

}
Pranav C Balan
  • 106,305
  • 21
  • 136
  • 157
1

You can get it with the regular expression in combination with .test() to check and .match() to extract the number:

var url = "http://localhost/admin/namespace_module/yeezy/index/test_id/5/key/23123asda/"; // window.locatioin.href;

if(/test_id\/[0-9]+/.test(url)){
   console.log(url.match(/test_id\/[0-9]+/)[0].match(/[0-9]+/)[0]);
   //--test_id/5---------^^^^^^^^^^^^^^^^^^^^^----5--^^^^^^^^^^^^
}  //--output-----------------------------------output-----------
Jai
  • 71,335
  • 12
  • 70
  • 93
  • The downside to this method is that it is not so efficient. Up to three times a regular expression is executed, while it can be done with one regular expression execution. – trincot Mar 14 '17 at 07:33
1

To get the number after testing for the pattern, do:

var match = window.location.href.match(/\/test_id\/(\d+)/);
if (match) {
    // pattern is OK, get the number
    var num = +match[1];
    // ...
}
trincot
  • 211,288
  • 25
  • 175
  • 211