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

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.

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);

How to put "</script>" in a javascript string?

I've been trying some tricks in javascript and came to a ridiculous problem: I can't use <script> as a substring in a javascript string! Here is an example:
<html>
<head>
<script>
alert("<script></script>");
</script>
</head>
</html>
It supposed to print out <script></script>, but instead, I get this:
");
Printed out on the page, as HTML.
Question: How can I use <script> followed by </script> substrings in Javascript, and why is it acting that way?
Here is JSFiddle of it.
What's tripping you up is the </script>. The HTML parser doesn't recognize Javascript strings or nested <script> tags, so it's interpreting that as the closing tag for the initial <script>. That is, this part of the document is parsed as:
<script> (open tag)
alert("<script> (text node - contents of the script)
</script> (close tag)
"); (text node - plain text)
The second </script> is ignored, as there's no other <script> tag for it to close.
To work around this, break up </script so that the HTML parser doesn't see it. For instance:
alert("<script><\/script>");
or:
alert("<script><" + "/script>");
or just put the code in an external Javascript file. This issue only arises for inline scripts.
it is because of the \ I believe. i have no concrete explanation since I am a newbie to Javascript but this code should work:
alert("<script><\/script>");
came up with it using Java knowledge.. Haha since the \ is an escape key in many languages.
Alert(\<script>\</script>\)

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.

JQuery JSON data not displaying

I am having trouble displaying some jason from a page.
The data is there but I think it might have to do with this line:
document.write(fbResults.cats[0].title);
Here is the full html source:
<!DOCTYPE HTML>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$.getJSON('http://mydomain.com/api/get_cats', function(fbResults) {
document.write(fbResults.cats[0].title);
});
});
</script>
</head>
<body>
</body>
</html>
And here is the data that it's reading:
{"cats":[
{"id":"1","title":"mytitle1","colour":"#EE297C"},
{"id":"2","title":"mytitle2","colour":"#EE412F"},
{"id":"3","title":"mytitle3","colour":"#F5821F"},
{"id":"4","title":"mytitle4","colour":"#00AEEF"},
{"id":"5","title":"mytitle5","colour":"#00B495"},
{"id":"6","title":"mytitle6","colour":"#006476"}
]}
It is not displaying anything on the page.
On firebug console I get this error:
The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must to be declared in the document or in the transfer protocol.
No traces of the json data there
What I'm I doing whong?
You shouldn't document.write after the page has loaded (which is certainly the case here).
If you want to write it to the page, you'll need to create HTML and append it. Just replace the document.write:
$('body').append('<p>'+fbResults.cats[0].title+'</p>');
Update:
Your example makes a fully qualified URL call. Is that server the exact same one that you're running the page from? If it isn't the XHR will just eat the request (and sometime not tell you). If you need to go cross domain, you'll need to use JSONp. If you're attempting to run this locally while pulling data from the net, it'll break.
Try this
$.each(fbResults.cats,function(index,item){
document.write(item.title);
});
Working sample : http://jsfiddle.net/zWhEE/8/
its seems work for me please check this
http://jsfiddle.net/TxTCs/1/

Categories