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.
Test URL: https://home.dreamcodesnippet.com/sites/Dream/1234567/YeNeYo%20Analogie/Snipp/AllItems.aspx
Task:
On a click of a button, we want to do the following using JavaScript.
- We want to get the current URL.
- Extract the Dream number from the URL. In our sample it’s 1234567.
Presented Solutions
- 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“));
- *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/.
- Second Solution – using regex
- var testurl = window.location.href;
var numberPattern = /\/(\d+)\//g;
testurl = “” + testurl.match(numberPattern);
testurl = testurl.replace(/\//g,”);
- var testurl = window.location.href;
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:
- JavaScript Tester: http://js.do/
- Regular Expression Tester: https://regex101.com/r/zZ5xK0/13#javascript
Leave a comment