getting div content using javascript regex doesn't work - javascript

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-->

Related

var text = $html.find("script type='application/ld+json':contains('sameAs')").text();

var text = $html.find("script type='application/ld+json':contains('sameAs')").text();
i didn't understanding what does this means? i haven't seen this before . Can you tel me where this is used and why. If you have any idea then tell me.
It looks like it's just wrong. It probably should be:
var text = $html.find("script[type='application/ld+json']:contains('sameAs')").text();
The first part of the selector script[type='application/ld+json'] will match all elements in $html like:
<script type="application/ld+json">...</script>
The :contains('sameAs') modifier then restricts the result to elements that have the string sameAs somewhere in the contents.

Jquery switching elements while they are inside a variable

I'm having a little difficulty trying to switch 2 elements around with Jquery when they are inside a string variable.
eg:
var myString =
"<div class='chatMessage'>Something here
<div class='test'>My test</div>
<div class='anotherTest'> the other test</div>
Something there
</div>";
What I would like is to switch the two classes around, making "anotherTest" be infront of "test".
What I've tried so far is:
var myString =
"<div class='chatMessage'>Something here
<div class='test'>My test</div>
<div class='anotherTest'> the other test</div>
Something there
</div>";
var div1 = myString.filter('.test');
var div2 = myString.filter('.anotherTest');
var tdiv1 = div1.clone();
var tdiv2 = div2.clone();
myMessage = div1.replaceWith(tdiv2);
myMessage = div2.replaceWith(tdiv1);
However I receive the following error
t.replace is not a function
I was wondering how I would be able to achieve to switch the two divs around while still stored inside the variable before displaying it to the user?
You're making things harder on yourself by adding the constraint that this needs to be done by direct string manipulation. HTML is meant to be rendered into the DOM -- and since that's a "document object model" it stands to reason it's better-suited for modelling your document as objects.
jQuery may seem a bit old-hat, but its whole purpose is to make querying the DOM easier, so it works well here. All you need to do is parse the string, query the node you want to move, and insert it before the element you want it in front of. You can get the HTML back using $.fn.html(), or you could just leave as an element if you're going to insert it somewhere on your page.
var $el = $(myString);
$('.anotherTest', $el).insertBefore($('.test', $el));
var myMessage = $el.html();
jsfiddle here
Try this one. Just split the string by "</div>", it will make an array of splited contents, then re-add "</div>" to each splited string (this will be consumed in the process of splitting).
Then reassemble.
https://jsfiddle.net/8a4wgn7k/
var myString = "<div class='test'>My test</div><div class='anotherTest'> the other test</div>";
var res = myString.split("</div>");
res[0] +="</div>";
res[1] +="</div>";
var switchedString=res[1]+res[0]

How to remove element from HTML string?

This doesn't seem to be working, I get an Uncaught Type error on the .remove() line:
JS:
var str = $("a").html();
var $html = $.parseHTML(str);
$("i",$html).remove();
$("div").html($html);
HTML:
Hello <i>Bob</i>
<div></div>
How to get this to work?
You can remove the HTML tags by just using the .text() function.
var str = $("a").text();
$("a").text(str);
Which will result in:
Hello Bob
Example: http://jsfiddle.net/3s1c55w2/
How it works:
The $("a").text(); will retrieve only the text of the element, so in your case it will return Hello Bob.
Once you retrieve Hello Bob, simply set the a tags text value using .text(str) again, where the str is the value with no html tags.
You can clone a, change html code of clone and put clone inside div.
Fiddle.
$(document).ready(function()
{
var clone = $("a").clone();
clone.find("i").remove();
$("div").html(clone);
});
Maybe he's trying to remove i tags from every anchor.
http://jsfiddle.net/1fytum86/
$("a").each(function(index) {
var str = $(this).text();
$(this).html(str);
});
Anyway, it's possible that he was getting a type error because parseHTML() parses a string into an array of DOM nodes. Best of luck!
If you are trying to remove the italics and leave the text:
$("a").html($("a").html().replace(/<\/?i>/g, ""));
Otherwise, the other answers using either remove or detach would be appropriate.

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