Friends from SharePoint Team asked for my help on how to get the current page’s URL and extract certain part of it for their use.
Task:
On a click of a button, we want to do the following using JavaScript.
  1. We want to get the current URL.
  2. Extract the Dream number from the URL. In our sample it’s 1234567.

Presented Solutions 

  1. First Solution – using substring
    • *On this case, we hardcoded Dream/ and /Ye since we want to get the number in between them. The 6 on +6 is the length in characters of Dream/.
      var testurl = window.location.href;
      var myurlnumber=testurl.substring(testurl.lastIndexOf(“Dream/“)+6,testurl.lastIndexOf(“/Ye“));
  2. Second Solution – using regex
    • var testurl = window.location.href;
      var numberPattern = /\/(\d+)\//g;
      testurl = “” + testurl.match(numberPattern);
      testurl = testurl.replace(/\//g,”);
I’m not sure which one would be faster in terms of performance and best on memory allocation – but my guess is that it’s the first one since it only needs to find 2 sets of characters. While, the second solution has to do RegEx match, then replace the forward slashes.
Helpful Links: