Javascript / jQuery - convert special html characters - javascript

I have a pre element with some html code in it.
the code has special characters in it, like <, so it doesn't break the page.
Then I have a javascript function that gets the contents of this pre element, highlights it (with codemirror), and replaces the element contents with the highlighted text.
I'm using $("pre").append(...); to do this.
The problem is that after the highlighting, on the screen I see < instead of <.
How can I convert these characters back to html?

You should be using the .text() method to grab the code from the pre. This way you are't giving the encoded symbols to the code highlighter.

I don't know what happens (and why it happens) to your html, but you can use jQuerys .text() and .html() to decode/encode html entitiys like:
HTML
<div id="test"><<</div>
jQuery:
var t = $('#test');
t.html(t.text()); // will print "<<"
example: http://www.jsfiddle.net/fphw3
update
Since you mentioned that you use .html() to read the value of your element, a call to .text() instead should solve your issue.

Related

Remove script elements from html string converting query string to symbol

I am using this solution here to remove script elements from ajax responses. However, when my response looks like this :
'console.log("test");https://x.ya.com/home?abc=1&currency=EUR'
It converts the &curren to ¤ symbol.
The result looks like this:
'https://x.ya.com/home?abc=1¤cy=EUR'
How do I avoid this?
Try using the escaped ampersand & to represent the character & in the HTML where this problem occurs, like so;
HTML
Example Link
Produces
Example Link
I used the approach as mentioned in the answer here. This removes all the script elements from the text without treating it as html (without creating a div and appending the text to innerHTML of the div), which solves the case.
No html = no html symbol decode.
Works for me!

Javascript HTML escaping but preserving linebreaks

I have written a small jQuery script to help me build a styleguide. The script is used to copy and escape a piece of HTML and print it as documentation. My problem, however, is preversing linebreaks in the html. I would love for my escaped HTML to be formatted just like I have typed it. How is that possible?
$('.documentation-element').each(function() {
var HTML = $(this).html();
$(this).next().find('code').text(HTML).html();
});
See full example here:
http://jsfiddle.net/tolborg/nr7fs/
Change the text() method to html():
$(this).next().find('code').html(HTML);
JSFiddle
You're using a <code> tag, but that doesn't preserve line breaks. You need a <pre> tag for that. So wrap your <code> tag inside a <pre> tag and your code should work as is - except you don't need the extra .html() at the end (it doesn't hurt anything, it just doesn't do anything):
$('.documentation-element').each(function() {
var HTML = $(this).html();
$(this).next().find('code').text(HTML);
});
Here's an updated fiddle.
You may also want to tweak the leading whitespace on each line, but what you want there will depend on the output you want.
For example, here's a version that strips leading whitespace and also removes the extra newlines at the beginning and end:
$('.documentation-element').each(function() {
var HTML = $(this).html().trim().replace( /\n\s+/, '\n' );
$(this).next().find('code').text(HTML);
});

jQuery get html in div without any markup

I have some script written using the jQuery framework.
var site = {
link: $('#site-link').html()
}
This gets the html in the div site-link and assigns it to link. I later save link to the DB.
My issue is I don't want the html as I see this as being to dangerous, maybe?
I have tried:
link: $('#site-link').val()
... but this just gives me a blank value.
How can I get the value inside the div without any markup?
Try doing this:
$('#site-link').text()
From the jQuery API Documentation:
Get the combined text contents of each element in the set of matched
elements, including their descendants, or set the text contents of the
matched elements.
Use the .text() jquery method like this:
var site = {
link: $('#site-link').text()
}
Here is an example of what .val(), .html() and .text() do: jsfiddle example
Use the text() method.
Get the combined text contents of each element in the set of matched elements, including their descendants, or set the text contents of the matched elements.
Use the .text() function of jQuery to get the only text.
var site = {
link: $('#site-link').text()
}
to avoid html, you will be required to use text() method of jquery.
var site = {
link: $('#site-link').text()
}
http://api.jquery.com/text/
If you are planning to store the result in the database and you are concerned about HTML, than using something like .text() rather than .html() is just an illusion of security.
NEVER EVER trust anything that comes from the client side!
Everything on the client side is replaceble, hijackable by the client rather easily. With the Tamper Data firefox plugin for example, even my mother could change the data sent to the server. She could send in anything in place of the link. Like malicious scripts, whole websites, etc...
It is important that before saving the "link" to the database you validate it on the server side. You can write a regex to check if a string is a valid url, or just replace everything that is html.
It's also a good idea to html encode it before outputting. This way even if html gets into your database, after encoding it will be just a harmless string (well there are other stuff to be aware of like UTF-7, but the web is a dangerous place).

Preserving white space in an HTML select option

I have a set of html text boxes that take input and when the user clicks an 'add' button uses javascript to take the text input and format a string that is put in an HTML select box. The first of these boxes is supposed to contain a 2 character number but can also accept a blank. The formatted strings would look like this:
01-ABC-O
02-DEF-I
However I need a way to display the blank numbers that lines up with the other elements
-GHI-O
This type of entry will show up fine when the javascript adds the option, but when the page is reloaded and the select is repopulated with the values (I'm using Java, jsp, and struts 1.1 if that helps) it gets the same values(spaces preserved) but the whitespace is no longer shown in the select control (I've looked at the page source, and it looks identical to when the javascript adds the option). I have tried substituting the spaces for but this just prints the string "&nbsp" instead of the space. I've also tried using "pre" html blocks and the css white-space property and neither have worked.
Let me know if any further clarification is needed.
You need to replace the spaces with and it should work - note the closing semi-colon (which is missing from your example in the question)! When you do it through Javascript, most (all?) browsers will automatically render the spaces, but when the spaces are there when the page is loaded all (sometimes all but one) of them will be ignored.
You should also apply a font-family: CSS attribute to the select that specifies mono-spaced font(s) in order to ensure everything lines up properly.
When creating the select option with javascript, to preserve white-space, use "\xa0" - it is a NO-BREAK SPACE char.
You can use the pre css style on the area that you are outputting the value to.
<style type="text/css">
#element {
white-space: pre;
}
</style>
<div id="element">
stuff goes here
</div>
This will preserve all whitespace in the div element (other element types will also work) and then you don't need to worry about using the non breaking space.
Are you going to add it via scripting, you need to use Escape Codes for Space "% A0" which you then decode with unescape ()
logTypeList[i] = new Option(unescape(" kent Agent".replace(/ /g, "%A0")), "theValue");
logTypeList[i] = new Option(unescape(" kent Agent".replace(/ /g, "%A0")), "theValue");
Since unescape is deprecated, you may want to use decodeURI:
logTypeList[i] = new Option(decodeURI(" kent Agent".replace(/ /g, "%C2%A0")), "theValue");
More info at http://www.javascripter.net/faq/mathsymbols.htm
You can use the Unicode Character 'SPACE' (U+0020) instead of ("\u0020")

"<" sign not showing in javascript?

I have a div-element that I want to show the symbol '<'.
div-element.innerHMTL = '<';
The string actually do not appears, I think the problem lies in that the browser thinks that it is a beginning of a tag element
Anyone seen this problem before?
You should use an HTML entity - <. This will be displayed by the browser as <, rather than being interpreted as the start of an HTML tag.
Here's a handy list of common HTML entities: http://www.danshort.com/HTMLentities/
divElement.innerHTML = '<';
innerHTML sets does not encode and can be used to set html elements.
innerText sets encodes and cannot be used to set html elements.
You should use innerText when you just want to set text or you should encode the text when you want to mix html with text
This might be useful link which shows all symbols
http://www.w3schools.com/HTML/html_entities.asp

Categories