-1

The following code is used to get URL parameters.

<script type="text/javascript">
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
</script>

<script type="text/javascript">
var url = window.location.protocol + "//" + window.location.hostname;
</script>

The page with the above code is accessed from a link on another page. Within that link i'm passing in a news item ID and Title. When the page with the above code loads the Title in the URL has %20 in place of all spaces. I've read up on this and found i need to use decodeURI or decodeURIComponent. I've tried to do this in a number of places and alerted the result in the browser but i can't seem to get rid of the %20 from the title within the URL so its obvious i'm not doing it in the right place.

this is my result....

http://PAGE URL HERE/NewsArchive.aspx?Story=New%20site%20launched&ID=17

I believe i somehow need to include a regular expression of /%20/g,"-" in the replace of the parts variable, however i have next to no knowledge of regex.

Could someone let me know what i need to do as i'm drawing a blank. I've seen a number of similar articles but nothing that explains it to my low level of knowledge.

I also post on SharePoint Stack Exchange as this is being used with SharePoint but i haven't had any answers that have worked for me.

Any help appreciated.

Ian
  • 23
  • 1
  • 6

1 Answers1

0

I am not sure I understand the question, but it seems like you just want to retrieve the parameters? If you open the developer console (f12 in chrome) on the page with parameters in the URL you can type window.location and see all the properties of the object. If you type window.location.href you can see the full URI. An easy way to separate this is using .split.

window.location.href.split('?')[1] will give you everything after the ? character. You can do decodeUri(window.location.href.split('?')[1]) to get a normal string.

Just keep in mind the arrays returned by split are zero indexed.

Edit in response to the comment: The technology you're looking for is history.replaceState. More details here. I would highly recommend a thorough skimming.

history.replaceState(null, "/NewsArchive.aspx", "Story=New-site-launched&ID=17")
John Pavek
  • 2,595
  • 3
  • 15
  • 33
  • 1
    `window.location.href.split('?')[1]` == `location.search.slice(1)` – dandavis Jun 21 '17 at 21:19
  • Sorry my question is a little ambiguous. What i want to do is, when the page loads, is change the parameters in the URL from Story=New%20site%20launched&ID=17 to Story=New-site-launched&ID=17 Whatever i try and do i cannot seem to effect theURL – Ian Jun 21 '17 at 21:27
  • @Ian I updated my answer. Hopefully that is what you're looking for. – John Pavek Jun 21 '17 at 22:06