How to decode url-encoded string in javascript - javascript

I use javascript / jquery to fill dom elements that contain umlauts:
var text1 = "Unser platonisches Internetreich droht in die H%E4nde einer bewaffneten Miliz zu fallen."
$("#quote1 span").html(unescape(text1));
How can I get rid of the url encoding e.g. "H%E4nde" and use "Hände" instead? I tried
<meta charset="utf-8" />
<meta name="http-equiv" content="Content-type: text/html; charset=UTF-8"/>
<script type="text/javascript" src="js/index.js" charset="utf-8"></script>
But none of them seem to work...
Thanks for help.

That is not UTF-8, that is percent encoding also known as url encoding.
You can use decodeURIComponent() to convert it back before displaying it
$("#quote1 span").html(decodeURIComponent(text1));

Use either of the following built in JavaScript function to decode any encoded text. No need for jquery or any other library.
const text1 = "Unser platonisches Internetreich droht in die H%E4nde einer bewaffneten Miliz zu fallen."
console.log(decodeURI(text1))
console.log(decodeURIComponent(text1))
update:
In case you're wondering how to encode, decoded text, you can use another built in JavaScript function like so
console.log(encodeURI(text1))
console.log(encodeURIComponent(text1))

Related

Why are my special characters '>>' being replaced with diamonds with question marks?

here are the two lines of code in which I'm printing the special characters '>' and '>>'. however, they are being displayed as diamonds w question marks on the webpage.
paginationHtml = paginationHtml+\"<a href='javascript:void(0)' onclick='getCommentList(\"+next_page+\")'>Next› </a>&nbsp\";
paginationHtml = paginationHtml+\"<a href='javascript:void(0)' onclick='getCommentList(\"+page_count+\")'>Last» </a>&nbsp\";
Make sure your html file is saved in the same format you declare in the head section. If for instance your file is utf-8 encoded, put this in your html:
<head>
<meta charset="UTF-8">
</head>
If you use ansi encoding, then
<head>
<meta charset="ISO-8859-8">
</head>
... etc, but it should correspond. If you have the choice for your file encoding, go for utf-8.
To display special characters like › & », your simplest solution is to save and display all your documents in UTF-8.
3 Steps:
1. In your root .htaccess file, specify
AddDefaultCharset utf-8
AddCharset utf-8 .html .css .js
2. At the top of your .html document, just below <head>, add
<meta charset="utf-8">
3. Importantly, make sure that you are saving any documents from your text editor with UTF-8 encoding.
The problem was I needed to change the encoding of my file. In PHPStorm, go to 'File' then 'File Encoding'. For me, I needed to choose 'UTF-8' encoding. I converted the code and now the ">>" characters show up fine in the website!

How to convert html to javascript string markup

Is there an easy way to convert HTML to a string that I can use in Javascript code, in order to insert a piece of html in a code editor?
example HTML:
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h1>Title</h1>
<h2>Subtitle</h2>
<p>Some text goes here</p>
</body>
</html>
Becomes This:
<html>\n\n\t<head>\n\t\t <title>Hello World</title>\n \t</head>\n\n \t<body>\n \t\t<h1>Title</h1>\n \t\t\t<h2>Subtitle</h2>\n \t\t\t\t<p>Some text goes here</p>\n \t</body>\n\n </html>\n
But how do I automate the process, because bigger HTML files will be hard to convert them like this by hand. Is there an easy converter available?
So in essence: Can I convert HTML code to a single line, where new lines + tabs are preserved with \n and \t ?
The editor that you are copying from appears to be inserting special characters for new lines and tabs.
You could always use a minifier like this one:
http://www.willpeavy.com/minifier/
You would need to just convert the text into JSON. Line breaks, quotes, special characters, etc., would all be escaped for you.
Use whatever language and environment you're comfortable with - pretty much any language will have a JSON serializer.
For example, in C# and ASP.NET MVC:
string html = File.ReadAllText(#"C:\myfile.html");
string json = JsonConvert.SerializeObject(html);
The variable json now can be safely injected into a webpage, and it will include the necessary quotes and special escape characters:
var someText = #Html.Raw(json);

AJAX http GET request

I'm currently teaching myself some AJAX through jQuery.
I've written a straight forward get request to load in data from an xml file into a section with a class of container.
Here is my html file:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<section class="container">
</section>
<script src="http://code.jquery.com/jquery-1.11.0.min.js" type="text/javascript" charset="utf-8" async defer></script>
<script src="xmlFeed.js" type="text/javascript" charset="utf-8" async defer></script>
</body>
</html>
I am using a local xml file after i created to dummy post on a WordPress site and got the feed.
Here is the xml file:
<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
xmlns:content="http://purl.org/rss/1.0/modules/content/"
xmlns:wfw="http://wellformedweb.org/CommentAPI/"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
>
<channel>
<title>Biz-Tech.ie » Biz-Tech News</title>
<atom:link href="http://www.biz-tech.ie/category/biz-tech-news/feed/" rel="self" type="application/rss+xml" />
<link>http://www.biz-tech.ie</link>
<description></description>
<lastBuildDate>Sat, 11 Oct 2014 17:39:16 +0000</lastBuildDate>
<language>en-US</language>
<sy:updatePeriod>hourly</sy:updatePeriod>
<sy:updateFrequency>1</sy:updateFrequency>
<generator>http://wordpress.org/?v=4.0</generator>
<item>
<title>News</title>
<link>http://www.biz-tech.ie/news/</link>
<comments>http://www.biz-tech.ie/news/#comments</comments>
<pubDate>Sat, 11 Oct 2014 17:39:16 +0000</pubDate>
<dc:creator><![CDATA[Michael]]></dc:creator>
<category><![CDATA[Biz-Tech News]]></category>
<guid isPermaLink="false">http://www.biz-tech.ie/?p=170</guid>
<description><![CDATA[Output Box – Random strings/passwords will display here. Load objects used for random string generation into the “Object Input Box” above. Objects above can be characters, words, sentences, etc. Test by clicking the “Generate random strings” button above to generate 10, 14 character, random strings from the default input objects. NOTICE: Tool uses Javascript method Math.random() pseudorandom generator to obtain […]]]></description>
<content:encoded><![CDATA[<p>Output Box – Random strings/passwords will display here.<br />
Load objects used for random string generation into the “Object Input Box” above. Objects above can be characters, words, sentences, etc.<br />
Test by clicking the “Generate random strings” button above to generate 10, 14 character, random strings from the default input objects.<br />
NOTICE: Tool uses Javascript method Math.random() pseudorandom generator to obtain random string. Do not use for critical random results.<br />
Privacy of Data: This tool is built-with and functions-in Client Side JavaScripting, so only your computer will see or process your data input/output.</p>
]]></content:encoded>
<wfw:commentRss>http://www.biz-tech.ie/news/feed/</wfw:commentRss>
<slash:comments>0</slash:comments>
</item>
</channel>
</rss>
And finally here is the ajax GET request along with a function to parse the xml into the container section in my html:
$(doccument).ready(function() {
$.ajax({
type:"GET",
url:"feed.xml",
dataType:"xml",
success:xmlParser
});
});
function xmlParser(xml) {
$(xml).find("item").each(function(){
$("#container").append('<h3>'+ $(this).find("title").text()+'</h3><br />'
'<a href="'+ $(this).find("link").text()+'></a>'
'<p>'+ $(this).find("description").text()+'</p>'
'<p><h5>Author: '+ $(this).find("dc:creator").text()+'</h5></p>'
);
});
}
The function isn't working and for the life of me I have no idea why as I can see an syntax errors.
Any advice would be greatly appreciated.
Thanks.
A few problems with your code.
1). The way you are concatenate strings in javascript is not correct. Use this syntax:
$(xml).find("item").each(function(){
$(".container").append('<h3>'+ $(this).find("title").text()+'</h3><br />' +
'' +
'<p>'+ $(this).find("description").text()+'</p>' +
'<p><h5>Author: '+ $(this).find('dc\\:creator, creator').eq(0).text()+'</h5></p>'
);
});
Note + operator, it is used for string concatenation.
2). One more problem. You missed a closing quote in link construction string, which breaks HTML and hides all subsequent content:
''
^-- add this guy here
3). One more thing: your selector must be $(".container") since container is a class, not id.
4). And finally there is one more little detail about how you should retrieve dc:creator node. Since this node is namespaced you need to escape it like this:
.find("dc\\:creator")
However it still doesn't guarantee that it will work in all browsers. You probably should do something like this:
$(this).find('dc\\:creator, creator').eq(0)
You provide two selectors here. The second selector creator will work in Chrome, and the first (escaped) in Firefox.
5). Also just in case, doccument is a probably a typo, but anyway it should be document.
Demo: http://plnkr.co/edit/0Z2tJJ3JANtJq30CNUDD?p=preview
You wrote doccument instead of document in your $(doccument).ready.
The key to your problem is "I am using a local xml file ...". If you look at your console I am pretty sure that you are getting an "Access-Control-Allow-Origin error". This is a browser model security problem. Have a read here if you need more info.
In short though Access-Control-Allow-Origin errors occurs when you call a Web Service such as do a GET request for an XML file, from a domain that is different from the one hosting your HTML page. In you case I believe that you are your HTML file is on your hard drive while the Web Service is called on the localhost.
For development purposes you can use this chrome plugin. That will work for now.

Pound (£) and euro (€) signs encoded wrong in external JavaScript file

I'm trying to encode the £ sign in an external JS file but I keep getting '%EF%BF%BD'. Here's the code in its simplicity:
alert(encodeURIComponent("£"));
The same alert gives me '%C2%A3' on the HTML page that is calling the external JavaScript file. The HTML page has the following character set:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
And I've defined the character set for the external JS file too:
<script type="text/javascript" src="/js/share.js" charset="utf-8"></script>
How can I force the external JavaScript file use UTF-8 encoding?
Fixed the problem by creating a blank JS file with UTF-8 encoding, copying the code in from the original file and replacing the old file with the new file.
ef bf bd is the replacement character - what a browser uses if it does not have the given character in its font.
If it renders correctly here, it looks like this: �
My guess would be that whatever font you're using does not support the British pound symbol £
Could you add a link to the page you're using or a demo?
Use UTF encoded character
alert("\u00A3");
On jsfiddle
UPDATE: I am still unsure as to what your problem is, but here is a further example.
HTML
<div id="out"></div>
Javascript
var link = "http://somewhere.com",
tweet = "£££££€€€€€€€",
x = 'anchor';
document.getElementById("out").innerHTML = x;
alert(decodeURIComponent(x));
On jsfiddle
As I suggested in the comments, you should construct a jsfiddle to demonstrate the issue you are having if the above is not the solution that you are looking for.

How can I read a JSON in the script-tag from JavaScript?

I have a dynamically generated page where I want to use a static JavaScript and pass it a JSON string as a parameter. I have seen this approach used by Google (see Google's +1 Button: How do they do it?).
But how should I read the JSON string from the JavaScript?
<html>
<head>
<script src="jquery-1.6.2.min.js"></script>
<script src="myscript.js">{"org": 10, "items":["one","two"]}</script>
</head>
<body>
Hello
</body>
</html>
In this JavaScript I would like to use the JSON argument {"org": 10, "items":["one","two"]} from the HTML document. I don't know if it's best to do it with jQuery or without.
$(function() {
// read JSON
alert("the json is:")
})
I would change the script declaration to this:
<script id="data" type="application/json">{"org": 10, "items":["one","two"]}</script>
Note type and id fields. After that
var data = JSON.parse(document.getElementById('data').textContent);
will work just fine in all browsers.
The type="application/json" is needed to prevent browser from parsing it while loading.
And the reason why we use textContent instead of innerHTML or innerText to read the raw Json text is because innerHTML tries to parse the contents as HTML which will lead to slower performance and possible parsing bugs and XSS attacks, and innerText won't grab the raw text and will instead look for human-visible text, whereas textContent grabs the pure text as-is (which is what you want). See https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent for more details about why innerHTML and innerText are bad.
I ended up with this JavaScript code to be independent of jQuery.
var jsonElement = document.getElementById('json-script-tag');
var myObject = JSON.parse(jsonElement.textContent);
To read JSON in <script id="myJSON"> use
var manifest= document.getElementById('myJSON').innerHTML; //sets manifest to the text in #myJSON
manifest= JSON.parse(manifest) //Converts text into JSON
You can also use methods to point to the script like document.scripts[0]
//var manifest= JSON.parse(document.getElementById('myJSON').innerHTML); /*Shortend of 2&3*/
var manifest= document.getElementById('myJSON').innerHTML; //Gets text in #myJSON
manifest= JSON.parse(manifest) //Converts it into JSON
document.getElementById('test').innerHTML= manifest.name+ '<br/>'+ manifest.otherOptions; //Displays it
console.log('manifest')
console.log(manifest);
<head>
<script type="application/json" id="myJSON">
{"name":"Web Starter Kit", "otherOptions":"directly here"}
</script>
</head>
<body>
<p id="test"></p>
</body>
JSON.parse($('script[src="mysript.js"]').html());
or invent some other method to identify the script.
Maybe instead of .html() you might need .text(). Not sure. Try them both.

Categories