Find Html Inside a String Using Jquery - javascript

I am not sure how practical this question is , but what i am trying to do is find html inside a string and then append pre tags to it using jquery. let say i have a variable with following string.
var string = "Some normal text <html><body><div> This is the html </div> </body></html>";
Html inside the string is dynamic and can contain any tags , what i want is to find the starting and ending of html and append,prepend pre tags accordingly.
Thanks

The following code does pretty much what you want, however it does not allow html, body tags etc. But those are not allowed in pre tags anyway.
var string = "Some normal text <html><body><div> This is the html </div> </body></html> more text<p>more html content</p>";
var holder = $('<div>').html(string);
holder.children().wrap('<pre>');
//Print result to console
console.log(holder.html());
Also a jsFiddle here: http://jsfiddle.net/evBCm/1/

Add the text to dynamic html tag e.g span or div and find desired node e.g
var string = "Some normal text <html><body><div> This is the html </div> </body></html>";
$("<span/>").html(string).find('div')

Apply bellow regix..
var string = "Some normal text <html><body><div> This is the html </div> </body></html>";
var iMatches = string.match("<html>(.*)</html>");
var iHtml='<html>'+iMatches[1]+'</html>';
alert(iHtml);

Related

How to get text data from froala editor?

Currently I use $('div#edit').froalaEditor('html.get') to retrieve the html data inside editor, but it sucks when it comes to process / store the text data in my backend because of all the p tags and &npsb; symbols in raw html string.
To be honest they do not even pass to the database without losing parts of the data. Is there a way or an api to directly extract the text data as a string with proper symbols like "\n\t" from the froala editor?
If you dont like p tags you should use the enter option:
$('div#froala-editor-br').froalaEditor({
enter: $.FroalaEditor.ENTER_BR
});
If you really would like to remove all tags you could use jQuery text method
jQuery($('div#edit').froalaEditor('html.get')).text()
Or you could use HTML options
var html = $('div#edit').froalaEditor('html.get') ;
var div = document.createElement("div");
div.innerHTML = html;
alert(div.innerText);
There is http://textversionjs.com/ library which can be used to convert HTML to plain text. It also keeps new lines.
<script src="textversion.js"></script>
<script>
var html = $('div#edit').froalaEditor('html.get');
var text = createTextVersion(html);
</script>
Honestly, the easiest way to do this is
var body = $('#body').froalaEditor('html.get');
alert($(body).text());
You can use stringify() method in JSON to convert the HTML form to a text form.
<script>
var html = $('div#edit').froalaEditor('html.get');
var text = JSON.stringify(html)
</script>
And you can store them in any backend and use them later.

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.

Get text from div, add some more text, save as variable

Here's what I've got:
<div id="fivearea">Something</div>
Then later:
var 5popup= $('#fivearea').text();
This makes 5popup = "Something".
However, I want to add some more text to what's in the div and save that as a variable. Psuedo-code:
var 5popup= $('#fivearea').text()+"some additional text";
What's the correct way to do this?
You will want to add to the current value of the variable like this:
5popup += "some additional text";
Replacing the text inside the node below:
<div id="testId">hello</div>
Can be accomplished as follows
$("#testId").html("good bye");
Resulting in the html:
<div id="testId">good bye</div>
Similarly the text inside the node can be saved to a variable as follows:
var myTest = $("#testId").html();
If you want to add to the text inside a node without deleting anything, this can be accomplished with the append function. Given the following html.
<div id="testId">hello</div>
The code:
$("#testId").append(" world");
Will result in the html:
<div id="testId">hello world</div>
I think this is what you want:
var text = $('#fivearea').text();
text += "Your text here";
$('#fivearea').text(text);
If you want to access the text, use the variable text. Hope this helped.

Appending HTML-encoded string as HTML, not as text

I'm trying to append this string:
<div> hello </div>
as an HTML node, but instead of appending HTML it just appends the text:
<div> hello </div>
How do I make jQuery append this as an HTML node, not just text?
I'd like a solution that works both for nested divs AND text, if possible.
// This is your string :)
var myString = "<div> hello </div>";
// This is a way to "htmlDecode" your string... see link below for details.
myString = $("<div />").html(myString).text();
// This is appending the html code to your div (which you don't have an ID for :P)
$("#TheDivIWantToChange").append(myString);
HTML-encoding lost when attribute read from input field
You can create a new div with .createElement('div'). Then simply change the new element's HTML.
$(document.createElement('div').html('<p>All new content.</p>'));
To attach the new element to the DOM either use element.append() or .appendTo(element) to append to your element of choice.
Maybe this is a bit verbose, but this is usually how I handle stuff like that:
var div = $(document.createElement("div"));
div.text(" hello "); //Or div.html(" hello ") if need be...
$("#divtoappendto").append(div);

javascript: extracting text from html

I am getting html content as below:
var test='<div id="test">Raj</div>';
How can i retrieve value Raj from above html content using javascript.
It sounds like you're trying to extract the text "Raj" from that HTML snippet?
To get the browser's HTML parser to do your dirty work for you:
// create an empty div
var div = document.createElement("div");
// fill it with your HTML
div.innerHTML = test;
// find the element whose text you want
test = div.getElementById("test");
// extract the text (innerText for IE, textContent for everyone else)
test = test.innerText || test.textContent;
Or in jQuery:
test = $(test).text();
If you use jQuery (I cannot believe I just said that ;)) you can get at the content immediately you wrap it in $(test).html
Someone else will tell you how to get at the innerHTML using a selector since everybody here are jQuery gurus but me
Update: somebody just did while I was editing: javascript: extracting text from html - see comments or updates to that
var test = getElementById('test')
try that

Categories

Resources