Search code examples
javascriptriot-games-api

Javascript replace plus sign with space (but not %20)


I am trying to use the League of Legends API and request data on a certain user. I use the line

    var user = getUrlVars()["username"].replace("+", " ");

to store the username. However, when I do the XMLHttpRequest with that username, it'll put %20 instead of a space.

y.open("GET", "https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/"+user, false);

Edit: When I run this code with a user that has no space in their name it works, however when they have a space in their name it says the user is undefined.

For example, if I was looking for the user "the man", it would do a get at

https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/the%20man

But the correct request URL is

https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/the man

Solution

  • When you're creating a URL, you should use encodeURIComponent to encode all the special characters properly:

    y.open("GET", "https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/"+encodeURIComponent(user), false);