Javascript replacing HTML char code with actual character - javascript

I have a HTML input text, and its values are populated from a related div. My problem is that the div contains characters like & which will display correcly as '&' sign in div but when copied to text box the text '&' will be dispalyed
How can i convert & to & and '<' to '<', ' ' to ' ' ???

You thus want to unescape HTML entities. With plain JS you can use this snippet:
function unescapeHTML(html) {
var div = document.createElement("DIV");
div.innerHTML = html;
return ("innerText" in div) ? div.innerText : div.textContent; // IE | FF
}
And with jQuery the following one:
function unescapeHTML(html) {
return $("<div />").html(html).text();
}
But you can also just fix this problem during the step that you "copy" the div's content into the input element's value. Instead of grabbing HTML, just grab text. Instead of element.innerHTML, that'll be element.innerText for IE or element.textContent for real browsers.
No, you can't and shouldn't do this (reliably) with regex.

I am not sure how you are accessing data but a possible solution could be use of innerText property instead on innerHtml

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.

Div String replacement using RegEx

Hi I am using the following code :
breakContent = breakContent.replace(/<div>/g, ' <div>');
Here breakContent is a string that contains html code. I need to provide space before div tag.The above code works fine for div without any attribute like id, style,etc...
So what I need is the working code including attributes in div tag...
I tried the below code..but it does not give space before div and instead it replace the div with space
breakContent = breakContent.replace(/<div\s*[\/]?>/gi, " ");
Just change it to:
breakContent = breakContent.replace(/<div/g, ' <div');
Removing the trailing > will allow for <div> tags with attributes.
EDIT: Of course, this could pick up text that isn't actually a <div> tag, if you have text matching <div that isn't a tag.

Javascript : Replace Detect a string and replace html in a div after changing color

I am trying to change color of a part of strings. I have a list of DOM elements, and for each of them, the text can contain some hashtags. I would like to put in color all hashtags words which could be found in the text.
Here is the begin of the code :
var listOfText = document.getElementsByClassName("titleTweet");
for (var nodetext in listOfText) {
var divContent = listOfText[nodetext].innerHTML;
if (divContent.indexOf("#") !== -1) {
// Do job here
}
}
For example, divContent can be equals to "Hello my #friends ! How are you ?"
I would like to update the dom elements to put in red color the word "#friends".
I don't know how to do that using javascript or jQuery.
You can use a regexp to find the hastags and wrap them with html. Then use the .html() method to replace the original element's html with the new string.
Example snippet
$('#myDiv').replace(/#[a-z0-1A-Z]+/g, '<span style="color: red;">$&</span>'));
Working example - http://jsfiddle.net/4p4mA/1/
Edited the example to work on all divs on the page.
Note: This will only work so long as your element only contains text, because it is replacing all the child nodes with its text value.
use regex for this, find text having hashtag and replave that in span tag for each element.
$('.titleTweet').each(function(){
var $this=$(this);
$this.html($this.text()
.replace(/#[a-z0-1A-Z]+/g, '<span style="color: red;">$&</span>'));
});
See demo here
.innerHTML is a poor basis to starting replacing text. You'll want to navigate down to the text nodes and use .nodeValue to get the text. Then you can start splitting up the text nodes.

Keeping spaces in textarea (JavaScript variable)

I have a variable in JavaScript that contains the contents of an html textarea. When I print the variable all that were entered by the user are forgotten. Is there any way to find the spaces in the string so I can separate each line?
here is a function , you can use for your script:
function nl2br (str) {
var breakTag = ''; return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');
}
HTML collapses adjacent whitespace - so if you are displaying within HTML, that's what you are seeing.
You can replace spaces with non break spaces: - this will ensure they are displayed in HTML and not collapsed.
Another option is to place them in a <pre> element
You mean all newlines? HTML ignores newlines and collapses whitespace by default. Print them inside a <pre> tag, or check out the CSS white-space property: http://www.w3schools.com/cssref/pr_text_white-space.asp
You can also replace newlines with <br> tags using:
while (str.indexOf("\n") > -1) str = str.replace("\n","<br>");

Escaping html entities in textarea

I have a textarea used for comments that loads the contents of a div when a link is pressed, putting those contents in the displayed textarea.
Everything worked fine until I introduced a way to display interpoints (I'm talking about the · entity). These display fine in the div, but the problem is they also display as dots in the actual textarea, which I don't want. I want them to display as {*} in the textarea, since this is the string that gets converted to · on the server side.
This is the function I use to handle the display of tags:
function HtmlDecode(str)
{
var ta = document.createElement("textarea");
ta.innerHTML = str.replace(/</g, "<").replace(/>/g, ">").replace(/·/g, "{*}");
toReturn = ta.value;
ta = null;
return toReturn.replace(/<br\s*\/?>/mg, "\n");
}
I output the textarea like this:
anotherDiv.innerHTML = '<textarea ...>' + HtmlDecode(div.innerHTML) + '</textarea>';
What I don't understand is why if I change the /·/g replace with /asdf/g for example, any asdf will get replaced just fine.
Bottom line: how can I make my textarea display {*} instead of an actual interpoint?
What about .replace(/·/g, "{*}") instead of .replace(/·/g, "{*}");?

Categories

Resources