escape less / greater than javascript - javascript

I'm having a problem trying to escape some code... Basically, I want to escape "<" and ">" but I want them to APPEAR in my #output div as "<" and ">". Currently, they appear as as "<" and ">" on the page.
This is obviously to prevent anyone exploiting / injecting scripts on the page. This is my code:
var textval = $("#textarea").val(); //textarea
filtered = textval.replace(/</gi,"<"); //replace "<"
$("#output").html(filtered); //insert textarea data into div
Can anybody spot what I am doing wrong, or are there any better ways of doing this?
Many thanks
EDIT: I do want SOME html tags (like <b> to work, so I can't use $.text(); unfortunately..)

Try this:
var textval = $("#textarea").val();
$("#output").text(textval);
jQuery offers two methods - $.text() and $.html() where the method names speak for themselves :)

A little different replace, but works for me (even with .html()).
Demo
var str = $('#textarea').val();
$('#result').html(str.replace(/<|>/ig,function(m){
return '&'+(m=='>'?'g':'l')+'t;';
}));
<textarea id="textarea">
Hello, <b>World</b>!
</textarea>
<div id="result"></div>
(This is just to verify it can be done, .text() is the better approach)

Related

How to render only parts of a string as HTML

I want to render a text as common HTML and parse occurrences of [code] tags that should be output unrendered - with the tags left untouched.
So input like this gets processed accordingly:
<p>render as HTML here</p>
[code]<p>keep tags visible here</p>[/code]
<p>more unescaped text</p>
I've regexed all code-tags but I have no idea how to properly set the text of the element afterwards. If I use jQuery's text() method nothing gets escaped, if I set it with the html() method everything gets rendered and I gained nothing. Can anybody give me a hint here?
Try replacing [code] with <xmp> and [/code] with </xmp> using regex or alike, and then use the jQuery html() function.
Note that <xmp> is technically deprecated in HTML5, but it still seems to work in most browsers. For more information see How to display raw html code in PRE or something like it but without escaping it.
You could replace the [code] and [/code] tags by <pre> and </pre> tags respectively, and then replace the < within the <pre> tags by & lt;
A programmatic solution based on Javascript is as follows
function myfunction(){
//the string 's' probably would be passed as a parameter
var s = "<p>render as HTML here</p>\
[code]<p>keep tags visible here</p>[/code]\
<p>more unescaped text</p>";
//keep everything before [code] as it is
var pre = s.substring(0, s.indexOf('[code]'));
//replace < within code-tags by <
pre += s.substring(s.indexOf('[code]'), s.indexOf('[/code]'))
.replace(new RegExp('<', 'g'),'<');
//concatenate the remaining text
pre += s.substring(s.indexOf('[/code]'), s.length);
pre = pre.replace('[code]', '<pre>');
pre = pre.replace('[/code]', '</pre>');
//pre can be set as some element's innerHTML
return pre;
}
I would NOT recommend the accepted answer by Andreas at all, because the <xmp> tag has been deprecated and browser support is totally unreliable.
It's much better to replace the [code] and [/code] tags by <pre> and </pre> tags respectively, as raghav710 suggested.
He's also right about replacing the < character with <, but that's actually not the only character you should replace. In fact, you should replace character that's a special character in HTML with corresponding HTML entities.
Here's how you replace a character with its corresponding HTML entity :
var chr = ['&#', chr.charCodeAt(), ';'].join('');
You can replace the [code]...[/code] with a placeholder element. And then $.parseHTML() the string with the placeholders. Then you can insert the code into the placeholder using .text(). The entire thing can then be inserted to the document (run below or in JSFiddle).
var str = "<div><b>parsed</b>[code]<b>not parsed</b>[/code]</div>";
var placeholder = "<div id='code-placeholder-1' style='background-color: gray'></div>";
var codepat = /\[code\](.*)\[\/code\]/;
var code = codepat.exec(str)[1];
var s = str.replace(codepat, placeholder);
s = $.parseHTML(s);
$(s).find("#code-placeholder-1").text(code);
$("#blah").html(s);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Text
<div id="blah">place holder</div>
Around
The code above will need some modifications if you have multiple [code] blocks, you will need to generate a unique placeholder id for each code block.
If you may be inserting untrusted structure code, would highly recommend using large random number for the placeholder id to prevent a malicious user from hijacking the placeholder id.

ng-bind-html get first letter of html content

I am having a situation where i am using ng-bind-html for html binding.
I would like to get the first charactor of html content excluding the html tags.
Below is my sample code.
<span class="first-letter">{{firstLetter}}</span>
<div id="myDiv" ng-CLoak data-ng-bind-html="trustAsHtml(data.ContentDescription)" class="{{currentFont}}"></div>
my html string would look like following
<p><span>hii my content</span></p>
the starting and ending tags are un predictable.
i would like to get first letter "h" not "<"
Thanks in advance.
You can let the browser strip html for you using the textContent property
function strip(html)
{
var tmp = document.createElement("DIV");
tmp.innerHTML = html;
return tmp.textContent || tmp.innerText || "";
}
and since you are interested only in that first letter, than you probably don't need the ng-bind-html :)
In case you want to highlight that first letter, then use CSS :first-letter
https://developer.mozilla.org/en-US/docs/Web/CSS/%3A%3Afirst-letter
You can remove HTML tags and simply access first letter as we do in an array like this.
var regex = /(<([^>]+)>)/ig
, body = "<p><span>hii my content</span></p>"
, result = body.replace(regex, "");
console.log(result[0]);
Using jQuery
console.log($('<p><span>hii my content</span></p>').text()[0]);
It will give you "h"
if your contet
<p class="first-letter"><span>hii my content</span></p>
then
$(".first-letter").text().substring(0,1)
would return you the first letter no matter how many levels of nesting are there within the class .first-letter

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]

how to process textarea multiple line input if user hit "enter/return" key

my coding:
...
<textarea name="TextArea1" id="TextArea" style="height ; width" ></textarea>
...
<script type="text/javascript">
var txt_element = document.getElementById("TextArea");
document.write (txt_element.childNodes[0].nodeValue);
</script>
...
but it doesn't recognize "enter/return" key hited instead it shows " "
Many thanks
To expand on Chris's answer, the problem is that the browser is rendering the text you write in the same way as it renders any other piece of html, which means white space (including carriage returns) is treated as a word separator, not a line or paragraph separator. And multiple consecutive white space characters are condensed down to a single space. This is explained further in the html spec.
This is different to how it treats text within a textarea element.
So as Chris suggested, you need to replace carriage returns in your string with html <br> elements:
var enteredText = document.getElementById("TextArea").value;
var updatedText = enteredText.replace(/\n/g, '<br />');
document.write(updatedText);
Note: you should be able to get the textarea's value directly with .value rather than saying .childNodes[0].nodeValue.
Note 2: I second what Chris said about document.write() - it is usually not the best option.
Note 3: If you're catering for non-Windows system you may also need to replace \r.
Text areas use \n to designate a new line, something along these lines should work:
string = document.getElementById("TextArea")childNodes[0].nodeValue;
string = string.replace(/\n/g, '<br />');
document.write('string');
Not sure if you're just goofing around, but I feel compelled to mention that generally speaking you should never use document.write().

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