javascript find div id inside string and delete it's content - javascript

I have a string with some variable html saved inside, among which a div with static id="time",
example:
myString = "<div class="class">blahblah</div><div id="time">1:44</div>"
How can I create a new identical string cutting off only the time? (1:44 in this case).
I can't look for numbers or the ":" because is not safe in my situation.
What i've tried without success is this:
var content = divContainer.innerHTML;
var jHtmlObject = jQuery(content);
var editor = jQuery("<p>").append(jHtmlObject);
var myDiv = editor.find("#time");
myDiv.html() = '';
content = editor.html();
console.log('content -> '+content);

var myString = '<div class="class">blahblah</div><div id="time">1:44</div>';
//create a dummy span
//put the html in it
//find the time
//remove it's inner html
//execute end() so the jQuery object selected returns to the span
//console log the innerHTML of the span
console.log($('<span>').html(myString).find('#time').html('').end().html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

You can achieve this using a regular expression in plain javascript like so:
myString.replace(/(<div id="time">).*(<\/div>)/, '$1$2')
If you want to extract only the 1:44 portion you can use the following:
myString.match(/(<div id="time">)(.*)(<\/div>)/)[2]

Related

Strip certain html tags and return the rest of the string with all the other tags

I have a basic string with HTML tags in it. I want to remove the "span" tag and all of its contents and return the rest of the string and html.
When I do the following, it returns "here"...which is the contents of the matched query...I want to get everything else not the "span" stuff...what am I doing wrong?
var temp = '<div>Some text</div><p style="color:red">More text<span>here</span></p><p>Even more</p>';
var clean_temp = $(temp).find('span').remove();
var $temp = $(clean_temp).html(); //Returns "here"
alert($temp); // "here"
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
The jQuery remove() function removes and item and then returns the removed item, as you already seem to have discovered. The object from which it was removed is still also there, with its content modified.
Also in this case, due to the nature of your source string, doing $() on the source string returns a jQuery collection that wraps 3 separate DOM elements. Doing .find('span').remove() on that collection modifies the middle of these wrapped DOM elements. To reconstruct the HTML, we have to generate HTML from each wrapped DOM element and then join all these HTML parts together.
I created a helper function getHtml() for that purpose, see demo:
function getHtml(jqueryObj) {
return jqueryObj.toArray().map(el => el.outerHTML).join("");
}
var temp = '<div>Some text</div><p style="color:red">More text<span>here</span></p><p>Even more</p>';
var $temp = $(temp);
console.log(getHtml($temp));
$temp.find('span').remove();
console.log(getHtml($temp));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You can replace it with an empty string:
var temp = `
<div>Some text</div>
<p style="color:red">
More text <span>here</span>
</p>
<p>
Even more
<span>here as well</span>
</p>`;
// The modifier g looks global, not just the first hit and i is for case-insensitive
var expression = new RegExp(/<span(.*?)<\/span>/gi) // no closing '>' for elements with attributes
var clean_temp = temp.replace(expression, '')
console.log(clean_temp);

How to extract an array of all HTML tags from a textbox using javascript

I want to extract all the HTML tags like from this <body id = "myid"> .... </body> i just want to extract <body id ="myid"> similarly i want to extract all the HTML tags with attributes and using javascript.
I've tried using regex to make an array of all the tags inclosed between '< & >'
<script>
$(document).ready(function(){
// Get value on button click and show alert
$("#btn_parse").click(function(){
var str = $("#data").val();
var arr = str.split(/[<>]/);
$('#result').text(arr);
});
});
</script>
but it's creating an array arr containing empty and garbage also it's removing angular brackets '<>'
which I don't want.
SO in nutshell I want a script that takes
str ='mystring ... <htmltag id='myid' class='myclass'>i_don't_want_anythin_from_here</htmltag> ...';
and produces an array like:
arr = ["<htmltag id='myid' class='myclass'>","</htmltag>",...];
Here is one dirty way. Add it to the dom so it can be accessed via normal DOM functions, then remove the text, and split the tags and push to an array.
str ="mystring ... <htmltag id='myid' class='myclass'>i_don't_want_anythin_from_here</htmltag> ...";
div = document.createElement("div");
div.innerHTML = str;
document.body.appendChild(div);
tags = div.querySelectorAll("*");
stripped = [];
tags.forEach(function(tag){
tag.innerHTML = "";
_tag = tag.outerHTML.replace("></",">~</");
stripped.push(_tag.split("~"));
});
console.log(stripped);
document.body.removeChild(div);
Assuming you can also get the input from a "live" page then the following should do what you want:
[...document.querySelectorAll("*")]
.map(el=>el.outerHTML.match(/[^>]+>/)[0]+"</"+el.tagName.toLowerCase()+">")
The above will combine the beginning and end tags into one string like
<div class="js-ac-results overflow-y-auto hmx3 d-none"></div>
And here is the same code applied on an arbitrary string:
var mystring="<div class='all'><htmltag id='myid' class='myclass'>i_don't_want_anythin_from_here</htmltag><p>another paragraph</p></div>";
const div=document.createElement("div");
div.innerHTML=mystring;
let res=[...div.querySelectorAll("*")].map(el=>el.outerHTML.match(/[^>]+>/)[0]+"</"+el.tagName.toLowerCase()+">")
console.log(res)

convert raw string source to html to use jquery selector

I have this source
<div class="page"><h1>First Page </h1></div>
How can I convert it to html and use selector like $('.page') ? I tried to assign above string to a variable then use html() it doesn't work.
You can parse your string in HTML, after that if you look the object returned, there's a data property on the first row who contain the html string with good format.
EDIT
You can get HTML object properties without append it to the DOM. Check my edited code.
var test = '<div class="page"><h1>First Page </h1></div>';
var testHTML = $.parseHTML(test);
var elemHTML = $(testHTML[0].data);
console.log(elemHTML.text());
You can try this :
var test = '<div class="page"><h1>First Page </h1></div>';
var testHTML = $.parseHTML(test);
$("body").html(testHTML[0].data);
$(".page").css("color","blue");
//Without append element in the DOM
var elemHTML = $(testHTML[0].data);
console.log(elemHTML.text());
//For count number of element you can use a container without append it to the DOM
var container=$("<div></div>");
container.append(elemHTML);
console.log(container.find(".page").length);
.page{
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
See comments, first we have to process the entities, then use the result as HTML:
// The string
var str = '<div class="page"><h1>First Page </h1></div>';
// A wrapper element to put it in
var wrapper = $("<body>");
// Process the character entities
wrapper.html(str);
str = wrapper.text();
// Convert the resulting HTML to a structure
wrapper.html(str);
console.log("Text of .page: ", wrapper.find(".page").text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
That's verbose for clarity; here's the concise version:
var str = '<div class="page"><h1>First Page </h1></div>';
var wrapper = $("<body>");
wrapper.html(wrapper.html(str).text());
console.log("Text of .page: ", wrapper.find(".page").text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can use following script for this
$('.page').html('<div class="page"><h1>First Page </h1></div>');
or
var htmlString = '<div class="page"><h1>First Page </h1></div>';
$('.page').html(htmlString);
Jquery automatically convert it to html

Conversion of html object to string failed using jquery

Tried to convert my parsed html object to string but it returned only the title. Would appreciate some input in this regard
var html = `<html><title>My title</title><head></head><body><h1>hello World</h1></body></html>`;
html = $.parseHTML(html);
//do something here
//after parse to object, revert back to string
htmlString = $(html).prop('outerHTML'); //this is not working
console.log(htmlString);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
try
var _html = `<html><title>My title</title><head></head><body><h1>hello World</h1></body></html>`;
_html = $(_html);
htmlString = $('<div></div>').append(_html).html() ; //this should work
console.log(htmlString)
;
I would create a new element, then append the html to it and finally print the html of the new element.
Try this:
var html = `<html><head><title>My title</title></head><body><h1>hello World</h1></body></html>`;
var fake_html = $( document.createElement('html'));
fake_html.html(html);
//As jQuery object, you can do whatever you want with this fake_html (here I just change the Title string)
fake_html.find('title').html("Title changed");
htmlString = fake_html.prop('outerHTML');
console.log(htmlString);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Escape characters in String in a HTML page?

I have a string in the below non-escaped format in a HTML page:
<a href="http://somesite/product?page=blahk&id=EA393216&tabs=7,0&selections=quarter:Q2+2013^&wicket:pageMapName=wicket-2\">SomeThing</a>
What I need is to use jQuery/JavaScript to replace that string with just the link "SomeThing".
I have looked at some examples in StackOverflow, but they don't seem to work. I'm just getting started with jQuery and JavaScript, so would appreciate any help here.
Any ideas?
Try html() and text() in jquery to decode:
var str = '<a href="http://somesite/product?page=blahk&id=EA393216&tabs=7,0&selections=quarter:Q2+2013^&wicket:pageMapName=wicket-2\">SomeThing</a>';
var decoded = $('<div />').html(str).text();
alert($(decoded).text());
See Fiddle demo
var str = '<a href="http://somesite/product?page=blahk&id=EA393216&tabs=7,0&selections=quarter:Q2+2013^&wicket:pageMapName=wicket-2\">SomeThing</a>';
var helper = document.createElement('p');
// evaluate as HTML once, text now "<a href..."
helper.innerHtml = str;
// evaluate as HTML again, helper now has child element a
helper.innerHtml = helper.innerText;
// get text content only ("SomeThing")
alert(helper.innerText);
Here is a possible starting point.
Hope this gets you started!
function parseString(){
var str = '<a href="http://somesite/product?page=blahk&id=EA393216&tabs=7,0&selections=quarter:Q2+2013^&wicket:pageMapName=wicket-2\">SomeThing</a>';
var begin = str.indexOf('\">',0)+2; //--determine where the opening anchor tag ends
var end = str.indexOf('</a>',0); //--determine where the closing anchor tag begins
var parsedString = str.substring(begin,end); //--grab whats in between;
/*//--or all inline
var parsedString = str.substring(str.indexOf('\">',0)+2,str.indexOf('</a>',0));
*/
console.log(parsedString);
}
parseStr();

Categories