Check out the built-in function encodeURIComponent(str) and encodeURI(str).
In your case, this should work:
var myOtherUrl =
"http://example.com/index.html?url=" + encodeURIComponent(myUrl);
Answer from Buu on Stack OverflowHow to encode a string in JavaScript for displaying in HTML? - Stack Overflow
How can I json encode this string "[{"First":"Tom","Last":"Bowsen"}]"
[Javascript] Console escape character for a new line "\n" doesn't seem to work in Node
Use console.log.
More on reddit.comHow do I put a JSON object in a URL as a GET parameter?
JSON itself is a string. To turn your object into JSON you simply need to call a JSON.stringify(obj). Make sure you url-encode the string as well with encodeURI() before appending it to a link
More on reddit.comCheck out the built-in function encodeURIComponent(str) and encodeURI(str).
In your case, this should work:
var myOtherUrl =
"http://example.com/index.html?url=" + encodeURIComponent(myUrl);
You have three options:
escape()will not encode:@*/+encodeURI()will not encode:~!@#$&*()=:/,;?+'encodeURIComponent()will not encode:~!*()'
But in your case, if you want to pass a URL into a GET parameter of other page, you should use escape or encodeURIComponent, but not encodeURI.
See Stack Overflow question Best practice: escape, or encodeURI / encodeURIComponent for further discussion.
function htmlEntities(str) {
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}
So then with var unsafestring = "<oohlook&atme>"; you would use htmlEntities(unsafestring);
Do not bother with encoding. Create a text node using createTextNode instead. Data in text node is guaranteed to be treated as text. (from the docs: "This method can be used to escape HTML characters.")
document.body.appendChild(document.createTextNode("Your&funky<text>here"))