How to stop jQuery converting html entities into valid HTML? - javascript

Weeding out a few issues with my site when I found this curious issue.
<img src=".." width="1200" height="1200" alt="<script>alert("foo");</script>" />
The CMS appears to have done it's jobs and converted <script>alert('foo')</script> into what you see above. I display the caption with the following code.
site.caption = {
container : $('#caption'),
set : function(str) {
if (str && str.length) {
this.container.html('<span>'+str+'</span>').show(); console.log(str);
} else {
this.container.hide();
}
}
};
The function is called like this.
site.caption.set($(nextSlideElement).find('img').attr('alt'));
When this line runs an alert box pop's up with the text 'foo'. When I do the following in the site.caption.set function it shows the valid html.
console.log(str);
I am using jQuery 1.8.3. Does anyone know why this is happening? How do I show the text <script>alert('foo')</script> without it being run?

jQuery isn't converting it, the browser is when it parses the HTML.
If you want to treat a string as text instead of HTML, then use jQuery('foo').text(value) instead of jQuery('foo').html(value).

this.container.html('<span>'+str+'</span>')
Never concatenate HTML strings. Let jQuery do it for you. Get into this habit and you won't run into this problem.
this.container.empty().append($('<span/>').text(str));

Related

Write <script> or other tags as text in html [duplicate]

I want HTML, for example, <p>, to show show as just that, in plain text, and not interpreted by the browser as an actual tag.
I know JQuery has .html and .text, but how is this done in raw JS?
There are functions like encodeURIComponent that encodes <p> to %3Cp%3E but if I just put that into HTML, it interprets it literally as %3Cp%3E.
So there are also things like > and <, they work but I can't find any JavaScript functions that escapes & unescapes from this.
Is there a correct way to show HTML as text with raw JavaScript?
There's no need to escape the characters. Simply use createTextNode:
var text = document.createTextNode('<p>Stuff</p>');
document.body.appendChild(text);
See a working example here: http://jsfiddle.net/tZ3Xj/.
This is exactly how jQuery does it (line 43 of jQuery 1.5.2):
return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
The function used by Prototype looks like a good start:
http://www.prototypejs.org/api/string/escapeHTML
function escapeHTML() {
return this.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
}
Version more suited to use outside Prototype:
function escapeHTML(html) {
return html.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
}
You can use aslo innerText from most of DOM elements:
document.getElementById('some').innerText = "There can be <b> even HTML tags </b>";
The tags will not be formatted. You can aslo use \n for new line and more codes (\t, \u2623...). If you want aslo to use fixed-size characters you can use easy <pre> tag.
This is a job for the method createTextNode
var target div = document.getElementById('div1');
targetDiv.appendChild(document.createTextNode('<p>HelloWorld</p>'));
i suggest to use pre tag of html
and you can convert your using this link
e.g if you copy
<p>Hi </p>
it will give you converted code as...
<p>Hi </p>
Just copy and paste above code in pre and it will work fine...

Inserting HTML character entities with JQuery

I'm trying to create a tool that allows me to insert different Spanish characters into a text box such as the inverted question mark. I've currently got the following, but this returns:
function (e){var n,r,i,o=this[0];{if(arguments.length)return i=x.isFunction(e),this.each(function(n){var o;1===this.nodeType&&(o=i?e.call(this,n,x(this).val()):e,null==o?o="":"number"==typeof o?o+="":x.isArray(o)&&(o=x.map(o,function(e){return null==e?"":e+""})),r=x.valHooks[this.type]||x.valHooks[this.nodeName.toLowerCase()],r&&"set"in r&&r.set(this,o,"value")!==t||(this.value=o))});if(o)return r=x.valHooks[o.type]||x.valHooks[o.nodeName.toLowerCase()],r&&"get"in r&&(n=r.get(o,"value"))!==t?n:(n=o.value,"string"==typeof n?n.replace(V,""):null==n?"":n)}}¿
HTML
<div class="container">
<textarea id="text"></textarea>
<div id="one">¿</div>
JS
$('document').ready(function() {
$('#one').click(function() {
$('#text').val($('#text').val + '¿');
});
});
Any ideas on why I'm receiving this output? Also do HTML entities work within textboxes, if not how would I do so? No errors appear in the console.
JSFiddle
$("#text").val is a function, which you are supposed to call.
That said, jQuery is massive overkill for such a trivial task:
document.getElementById('one').onclick = function() {
document.getElementById('text').value += "\u00bf";
}
Note that \u00bf is the appropriate JavaScript escape sequence for ¿ - bf being 191 in hexadecimal.
EDIT: Alternatively, just hold Alt and type 0191 on your keypad. This will produce ¿ directly where you are typing, instead of at the end of the input which is what your JS does.
Try this one. Worked in your fiddle.
$(function() {
$('#one').on('click', function() {
$('#text').val($('#text').val() + "¿");
});
});
Update: I posted spanish sign of question instead of its ASCII, changed $(document).ready to a shorter way $(function(), and added brackets after val().

Add code examples on your page with Javascript

I have a html code inside string
string_eng += '<b>Year Bonus</b> - bonus for each year</br></br>';
And I want to put this inside textarea, but when I do it, the result is:
- bonus for each year
It simply deletes all things inside the html tags. I just want to show all the code inside the string. I already tried <xmp>,<pre>, but none of them worked.
Thanks for any help.
EDIT.
Code with which I input data from the array to the textarea/code.
$('body').append('<code class="code_text"></code>');
for(var i=0; i<tag_list.length; i++){
var string='';
string+='---------------------------------------------------------------------------------\n';
string+='tag: '+tag_list[i][0]+'\n';
string+='nazwa_pl '+tag_list[i][1]+'\n';
string+='nazwa_eng '+tag_list[i][2]+'\n';
string+='tekst_pl '+tag_list[i][3]+'\n';
string+='tekst_eng '+tag_list[i][4]+'\n';
string+='\n\n\n';
$('.code_text').append(string);
}
I tried this using jsfiddle:
HTML
<textarea id="code"></textarea>
JavaScript
$(document).ready(function() {
var string_eng = '';
string_eng += '<b>Year Bonus</b> - bonus for each year</br></br>';
$("#code").html(string_eng);
});
Output (contained in textarea)
<b>Year Bonus</b> - bonus for each year</br></br>
Try it here: http://jsfiddle.net/UH53y/
It does not omit values held within tags, however if you were expecting the <b></b> tags to render as bold within the textarea, or the <br /> tags to render as line breaks, this wont happen either. textarea does not support formatting.
See this question for more information: HTML : How to retain formatting in textarea?
It's because you're using the jQuery .append method which seems to parse the string and insert it afterwards. I don't know jQuery at all, so there might be another special jQuery method, but here is a simple fix:
$('.code_text').append(document.createTextNode(string));
Edit:
I just read and tried the answer of Salman A. The "special jQuery method" exists and he used it. You can use this:
$('.code_text').text(string);

removing html tags from string

I am trying to remove the HTML tags from a string. Right now I am able to remove the complete HTML tags like for example <div class="test">dadsasdsad</div> gives me the output dadsasdsad.
But I'm unable to remove partial tags like class="test">dadsasdsad</div> or testing<div class=
The regular expression that Ive used is
strippedText[i] = fragments[i]
.replace(/<(?:.|\n)*?>/gm, '')
.replace(replaceAT, '<span style=font-weight:800>')
.replace(replaceET, '</span>');
Here fragments[i] contains the input <div class="test">dadsasdsad</div>;
strippedText[i] = fragments[i]
// full tags
.replace(/<[^>]+>/gm, '')
// partial tags
.replace(/^[^>]+>/gm, '')
.replace(/<[^>]+$/gm, '');
Note that ^ has different meanings: "not" within brackets, "start" outside brackets.
/gm should not be necessary for partial tags, but I left them as I don't know your context and how you're getting partial tags.
my simple JavaScript library has a function called "strip_tags()" which does the long work for you.
Just say that you have a sentence loaded with HTML formatting tags, and you want to remove them, simply do it like this:
strip_tags("<p>This <em>sentence</em> contains <strong>a lot</strong> of tags!</p>");
This will output "This sentence contains a lot of tags!" (tested on the documentation website).
To read more about this function, please read the documentation at http://docs.funcjs.webege.com/strip_tags().html and if possible, leave feedback through the Feedback Form on the website.
Hope this helps you and anyone else with the same problem! :)
Using javascript you can do this:
function removeHTMLTags(htmlString) {
if(!htmlString) { return; }
var mydiv = document.createElement("div");
mydiv.innerHTML = htmlString;
return mydiv.textContent || mydiv.innerText || '';
}
[Source]

Replace a empty space with " " using Jquery

I am looking around on the web but I am not finding anything useful. :(
I am having a problem that I don't understand. I am sure that I am doing something wrong, but I don't know well the syntax of jQuery to understand what is that I am not doing right.
I am using animations with JS and CSS 3, and I am having troubles with empty spaces between the words, and to solve this problems I have to find a way to substitute chars inside a string of text with something else. Like an empty space with a , or as a test that I was trying to do a "n" with a "xxxxx".
What I think that I am doing is:
when the page is loaded
Modify the string of any paragraph with the class .fancy-title that contains "n" with a text "xxxxx"
So:
$(document).ready(function(){
for(i=0; i< myLength+1; i++){
var charCheck = $(".fancy-title").text()[i];
if(charCheck == "n"){
charCheck.replace("n", "xxxxxxxx");
}
}
});
But I receive an error that it said:
charCheck.replace("n", "xxxxxxxx"); it is not a function
I am using jquery
and other scripts that are based on jquery to make animations, rotation and scaling... and they are all in the HEAD with jquery first to load.
What am I doing wrong? Manipulation in jQuery does it need a specific .js extension? I understood that was in the basic capability of jQuery, and looking at other examples all creates me the same kind of error.
I even tried
if(charCheck == "n"){
$(".fancy-title").text()[i] == " "
}
But simply the modification it is not applied on the page. I tried with innerHTML as well :(
I feel so incompetent...
Thank you in advance for any help.
$(document).ready(function(){
$(".fancy-title").each(function(i){
var text = $(this).html();
$(this).html(text.replace(/ /g, " "));
})
});
You have no problem with the replace part :).
$(document).ready(function(){
$(".fancy-title").each(function () { //for all the elements with class 'fancy-title'
var s=$(this).text(); //get text
$(this).text(s.replace(/n/g, 'xxxxxxxx')); //set text to the replaced version
});
});
Just a quick example, hope it works.
Have you tried the css style white-space:pre instead of replacing ' ' with ' '?
http://de.selfhtml.org/css/eigenschaften/ausrichtung.htm#white_space
It seems you are trying to replace a single character with a new string.
You might be able to get the right result by dropping the iteration and simply call .replace on the jQuery-object.

Categories

Resources