Write html block as a string - javascript

I want to display the html as the user entered it in a textarea (using Javascript) . Like this :
Every thing fine link
How can i do that without using a "pre" tag? I just want to avoid html interpretation.
Thank you

Just create a text node…
var node = document.createTextNode(a_string);
… and add it to the document somewhere…
document.body.appendChild(node);

So you have a string:
str='Every thing fine link ';
you replace the brackets:
str.replace('<', '<').replace('>', '>');
then write in to the document:
document.write(str);
or set an existing elements content:
elem.innerHTML = str;

You can set the textContent.
elem.textContent = "<div>foo</div>";
But for browser compatibility, you should do something like this at the start of your code:
var textContent = ('textContent' in document) ? 'textContent' : 'innerText';
And then use it like this:
elem[textContent] = "<div>foo</div>";

jQuery.html() will do this for you

Related

Regular expressions: grab part of string

So I got the following input inside my textarea element:
<quote>hey</quote>
what's up?
I want to separate the text between the <quote> and </quote> ( so the result would be 'hey' and nothing else in this case.
I tried with .replace and the following regular expression, but it did not achieve the right result and I can't see why:
quoteContent = value.replace(/<quote>|<\/quote>.*/gi, ''); (the result is 'hey what's up'it doesn't remove the last part, in this case 'what's up', it only removes the quote marks)
Does someone know how to solve this?
Even if it's only a small html snippet, don't use regex to do any html parsing. Instead, take the value, use DOM methods and extract the text from an element. A bit more code, but the better and safer way to do that:
const el = document.getElementById('foo');
const tmp = document.createElement('template');
tmp.innerHTML = el.value;
console.log(tmp.content.querySelector('quote').innerText);
<textarea id="foo">
<quote>hey</quote>
what's up?
</textarea>
You could also try using the match method:
quoteContent = value.match(/<quote>(.+)<\/quote>/)[1];
You should try to avoid parsing HTML using regular expressions.
<quote><!-- parsing HTML is hard when </quote> can appear in a comment -->hey</quote>
You can just use the DOM to do it for you.
// Parse your fragment
let doc = new DOMParser().parseFromString(
'<quote>hey</quote>\nWhat\'s up?', 'text/html')
// Use DOM lookup to find a <quote> element and get its
// text content.
let { textContent } = doc.getElementsByTagName('quote')[0]
// We get plain text and don't need to worry about "<"s
textContent === 'hey'
The dot . will not match new lines.
Try this:
//(.|\n)* will match anything OR a line break
quoteContent = value.replace(/<quote>|<\/quote>(.|\n)*/gi, '');

How to to replace a text in document with javascript

ok my guy
so i want to replace MY GUY to ALRIGHT with javascript how can i do that
I have tried using
document.getElementById('demo').parentNodes.replaceChild(my guy, alright);
If you want to replace some text inside your tag, just use innerHTML property.
var myhtml = document.getElementById('demo').innerHTML;
document.getElementById('demo').innerHTML = myhtml === 'my guy' ? 'alright' : myhtml;
Like so..
replaceChild works not with text, but with html nodes. Checkout this https://developer.mozilla.org/en-US/docs/Web/API/Node/replaceChild
You can replace the entire text using innerText:
document.getElementById('demo').innerText = 'all right';
If you need to replace an specific part of the string, look at the String.prototype.replace() method.

getting div content using javascript regex doesn't work

I got some html code as a response from an ajax call. And I want to get the content of a specific div. Here's the html:
<html>
.
.
<div id="div-test">
.
.
</div><!--/div-test-->
.
.
</html>
Note: I use the <!--/div-test> because div#div-test contains more divs.
And that's my regex:
/<div[^.]*id=\"div\-test\"[^.]*>(.*?)<\/div><\!\-\-\/div\-test\-\->/
But it doesn't work at all. When I try to match it, all I get is a null value. So, is my regex wrong or is there anything else I need to do?
If you're looking for a non-regex approach, and you don't want to append the content on the page directly, you can create a document fragment and search through there:
var content = ""; // HTML FROM AJAX
var div = document.createElement('div');
div.innerHTML = content;
ajax_element = div.firstChild;
var test_content = ajax_element.getElementById('div-test').innerHTML;
as a regex approach, as much as I could advise against it, this might fit your needs:
var search_id = "div-test";
var r = new RegExp("<div[^>]*?id=[^\"]*?[^']*?"+search_id+"[^\"]*?[^']*?[^>]*?((?s).*)<\/div><!--\/"+search_id+"-->");
You can use the regex :
<div[^>]*?id='div-test'[^>]*?>(.*?)<\/div><!--\/div-test-->
Output
Or if the makup is with "" you can use
<div[^>]*?id=\"div-test\"[^>]*?>(.*?)<\/div><!--\/div-test-->

How to find and replace text in between two tags in HTML or XML document using jQuery?

I want to find and replace text in a HTML document between, say inside the <title> tags. For example,
var str = "<html><head><title>Just a title</title></head><body>Do nothing</body></html>";
var newTitle = "Updated title information";
I tried using parseXML() in jQuery (example below), but it is not working:
var doc= $($.parseXML(str));
doc.find('title').text(newTitle);
str=doc.text();
Is there a different way to find and replace text inside HTML tags? Regex or may be using replaceWith() or something similar?
I did something similar in a question earlier today using regexes:
str = str.replace(/<title>[\s\S]*?<\/title>/, '<title>' + newTitle + '<\/title>');
That should find and replace it. [\s\S]*? means [any character including space and line breaks]any number of times, and the ? makes the asterisk "not greedy," so it will stop (more quickly) when it finds </title>.
You can also do something like this:
var doc = $($.parseXML(str));
doc.find('title').text(newTitle);
// get your new data back to a string
str = (new XMLSerializer()).serializeToString(doc[0]);
Here is a fiddle: http://jsfiddle.net/Z89dL/1/
This would be a wonderful time to use Javascript's stristr(haystack, needle, bool) method. First, you need to get the head of the document using $('head'), then get the contents using .innerHTML.
For the sake of the answer, let's store $('head').innerHTML in a var called head. First, let's get everything before the title with stristr(head, '<title>', true), and what's after the title with stristr(head, '</title>') and store them in vars called before and after, respectively. Now, the final line is simple:
head.innerHTML = before + "<title>" + newTitle + after;

Is there a way to convert HTML into normal text without actually write it to a selector with Jquery?

I understand so far that in Jquery, with html() function, we can convert HTML into text, for example,
$("#myDiv").html(result);
converts "result" (which is the html code) into normal text and display it in myDiv.
Now, my question is, is there a way I can simply convert the html and put it into a variable?
for example:
var temp;
temp = html(result);
something like this, of course this does not work, but how can I put the converted into a variable without write it to the screen? Since I'm checking the converted in a loop, thought it's quite and waste of resource if keep writing it to the screen for every single loop.
Edit:
Sorry for the confusion, for example, if result is " <p>abc</p> " then $(#mydiv).html(result) makes mydiv display "abc", which "converts" html into normal text by removing the <p> tags. So how can I put "abc" into a variable without doing something like var temp=$(#mydiv).text()?
Here is no-jQuery solution:
function htmlToText(html) {
var temp = document.createElement('div');
temp.innerHTML = html;
return temp.textContent; // Or return temp.innerText if you need to return only visible text. It's slower.
}
Works great in IE ≥9.
No, the html method doesn't turn HTML code into text, it turns HTML code into DOM elements. The browser will parse the HTML code and create elements from it.
You don't have to put the HTML code into the page to have it parsed into elements, you can do that in an independent element:
var d = $('<div>').html(result);
Now you have a jQuery object that contains a div element that has the elements from the parsed HTML code as children. Or:
var d = $(result);
Now you have a jQuery object that contains the elements from the parsed HTML code.
You could simply strip all HTML tags:
var text = html.replace(/(<([^>]+)>)/g, "");
Why not use .text()
$("#myDiv").html($(result).text());
you can try:
var tmp = $("<div>").attr("style","display:none");
var html_text = tmp.html(result).text();
tmp.remove();
But the way with modifying string with regular expression is simpler, because it doesn't use DOM traversal.
You may replace html to text string with regexp like in answer of user Crozin.
P.S.
Also you may like the way when <br> is replacing with newline-symbols:
var text = html.replace(/<\s*br[^>]?>/,'\n')
.replace(/(<([^>]+)>)/g, "");
var temp = $(your_selector).html();
the variable temp is a string containing the HTML
$("#myDiv").html(result); is not formatting text into html code. You can use .html() to do a couple of things.
if you say $("#myDiv").html(); where you are not passing in parameters to the `html()' function then you are "GETTING" the html that is currently in that div element.
so you could say,
var whatsInThisDiv = $("#myDiv").html();
console.log(whatsInThisDiv); //will print whatever is nested inside of <div id="myDiv"></div>
if you pass in a parameter with your .html() call you will be setting the html to what is stored inside the variable or string you pass. For instance
var htmlToReplaceCurrent = '<div id="childOfmyDiv">Hi! Im a child.</div>';
$("#myDiv").html(htmlToReplaceCurrent);
That will leave your dom looking like this...
<div id="myDiv">
<div id="childOfmyDiv">Hi! Im a child.</div>
</div>
Easiest, safe solution - use Dom Parser
For more advanced usage - I suggest you try Dompurify
It's cross-browser (and supports Node js). only 19kb gziped
Here is a fiddle I've created that converts HTML to text
const dirty = "Hello <script>in script<\/script> <b>world</b><p> Many other <br/>tags are stripped</p>";
const config = { ALLOWED_TAGS: [''], KEEP_CONTENT: true, USE_PROFILES: { html: true } };
// Clean HTML string and write into the div
const clean = DOMPurify.sanitize(dirty, config);
document.getElementById('sanitized').innerText = clean;
Input: Hello <script>in script<\/script> <b>world</b><p> Many other <br/>tags are stripped</p>
Output: Hello world Many other tags are stripped
Using the dom has several disadvantages. The one not mentioned in the other answers: Media will be loaded, causing network traffic.
I recommend using a regular expression to remove the tags after replacing certain tags like br, p, ol, ul, and headers into \n newlines.

Categories