KPO
KPO

Reputation: 880

How can I decode special characters in a JavaScript variable?

This is what I have:

            url: "http://someurl.com/' + variable.id + '/page.html",

When the page renders I get a console error that looks like this:

http://someurl.com/'%20+%variable.id%20+%20'/page.html

And that prevents a certain API call from happening. What can i do to make sure it is read as?

http://someurl.com/variable.id/page.html

Where variable.id actually is a value not a variable.

Upvotes: 0

Views: 508

Answers (3)

Fabian De Leon
Fabian De Leon

Reputation: 126

Hi you are wrong on the sintaxis.

you can use:

 var url = "http://someurl.com/";
 url += variable.id + "page.html";
 document.location.href = url;

Good luck!!

Upvotes: 0

liopic
liopic

Reputation: 153

Did you mean (notice the double quotes)?:

url: "http://someurl.com/" + variable.id + "/page.html"

Upvotes: 1

JAAulde
JAAulde

Reputation: 19560

You have mis-matched quotes causing your string syntax to be broken. This is causing the single quotes, spaces, plus signs, and variable name to be in the string instead of being evaluated and executed as a JS statement.

You need:

url: "http://someurl.com/" + variable.id + "/page.html",

Notice the removal of the single quotes before and after your plus signs, and insertion in their place of double quotes which match the ones you used at the start and end of your assembled URL.

A string must start and end with the same kind of quotation mark. Equally valid would be:

url: 'http://someurl.com/' + variable.id + '/page.html',

or

url: "http://someurl.com/" + variable.id + '/page.html',

or

url: 'http://someurl.com/' + variable.id + "/page.html",

As each string is using a matched set of quotation marks, regardless of which kind you use.

Upvotes: 1

Related Questions