Reputation: 81
I'm still new to JS and HTML5
So I have a URL that I store in a var
var Base_URL = "https://www.mywebsite.com/info?username";
Which is linked to a Database that has access to a username value that can contain spaces.
I parse this url into a function
function removeSpaceURL(url) {
var update = url.split(' ').join('%20');
return update;
}
It is not the best way I know but it works good enough for its purpose.
Where I'm stuck is that I want to return the update into a href reference so I can click it.
<p><a href="" onclick="removeSpaceURL(BASE_URL);return false;" >Survey</a></p>
<script>
var Base_URL = "https://www.mywebsite.com/info?username";
function removeSpaceURL(url) {
var update = url.split(' ').join('%20');
return update;}
</script>
When I try it on JSfiddle, I get the following error:
{"error": "Please use POST request"}
Upvotes: 1
Views: 1630
Reputation: 1074385
The correct thing is to have Base_URL
be a correctly-formed URL in the first place, which it isn't if there's a space in the username part of it.
But assuming you're stuck with it, it's quite simple to set an attribute on an element:
<p><a id="target-link" href="">Survey</a></p>
<script>
var Base_URL = "https://www.mywebsite.com/info?username";
document.getElementById("target-link").setAttribute(
"href", encodeURI(Base_URL)
);
</script>
Note using encodeURI
as suggested by emiliopedrollo rather than a simplistic replacement of just spaces. But that said, if parts of the URI have already been encoded correctly and only the username is the problem, encodeURI
might double-encode things. So if you just want to replace spaces:
document.getElementById("target-link").setAttribute(
"href", Base_URL.replace(/ /g, "%20");
);
Also note that return false
from an onclick
on a a
element will prevent the link from being followed, so I've left off the onclick
entirely.
Upvotes: 3