I have this string (not html but string):
<div class="rTag">ATINA</div><div class="rTag">BELMOPAN</div><div class="rTag">DAMASK</div><div class="rTag">FILIPINI</div><div class="rTag">BANGKOK</div>
Need to extract text value of rTag so result should be a new string:
ATINA,BELMOPAN,DAMASK,FILIPINI,BANGKOK
Any help?
This will set the content of #output to the new str, but you can do whatever you want after its joined.
var str = [];
var content = '<div class="rTag">ATINA</div><div class="rTag">BELMOPAN</div><div class="rTag">DAMASK</div><div class="rTag">FILIPINI</div><div class="rTag">BANGKOK</div>';
var $html = $($.parseHTML("<div>" + content + "</div>"));
$html.find(".rTag").each(function(){
str.push($(this).html());
});
$("#output").html(str.join(","));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<div id="output"></div>
Parsing an HTML string into a DOM element so that it can be processed by javascript/jquery is a fairly standard process:
$(content)
will suffice without needing to add it to the DOM (and all that entails behind the scenes).
In this case:
var content = '<div class="rTag">ATINA</div><div class="rTag">BELMOPAN</div><div class="rTag">DAMASK</div><div class="rTag">FILIPINI</div><div class="rTag">BANGKOK</div>';
var arr = $(content).filter(".rTag").map(function() {
return $(this).text();
}).get();
console.log(arr.join(","));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Related
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]
I'm trying to build a function, that receives a string with this format:
"hello wor**"
The * could be anywhere on the string.
It should return:
<span>hello wor</span><input type='text'></input>
So the string could be "hel** wor*d" also
and the return should be:
<span>hel</span><input type='text'> <span>wor</span><input type='text'><span>d</span>
I could do it easily with a loop on each char, but I'm looking for more elegant solutions.
I think that it could be solved with a regex, and using replace I got the "*" covered:
var text = "hello wor**";
text.replace(/\*+/g, "<input type='text'></input>");
I have not yet found a way of capturing the remaining text to render the
<span>
You're not using the result of the replace function. Try this:
var text = "*hel** wor*d*";
var element = text.split(/\s*\*+\s*/g);
element = "<span>"+ element.join("</span><input type='text'><span>") + "</span>";
element = element.replace(/<span><\/span>/g, "");
console.log(element);
'hello wor**'.replace(/\*+/g, "<input type='text'></input>");
This returns hello wor. All you have to do is concatenate the string with the rest of the data you want, like so:
var text = "hello wor**";
text = '<span>' + text.replace(/\*+/g, '') + '</span><input type=\'text\'></input>';
<html>
<head>
</head>
<body>
<span id="hi">hello wor**</span>
</body>
</html>
i use jquery in this
$( document ).ready(function() {
var texty = $('#hi').text();
$('#hi').replaceWith(texty.replace(/\*+/g, "<input type='text'></input>"))
});
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
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>
I have a string variable called the res.
Within this variable there is HTML code.
Each Div in variable within the has a id.
var res = "<div id="1">1</div>
<div id="2">12</div>
<div id="3">123</div>
<div id="4">1234</div>";
var content-div-1 = ??;
var content-div-2 = ??;
var content-div-3 = ??;
var content-div-4 = ??;
I would like to give the id of div and give me values of inside Div.
The question has been answered, but there's an alternative without jQuery
var res = '<div id="1">1</div>'+
'<div id="2">12</div>'+
'<div id="3">123</div>'+
'<div id="4">1234</div>';
function findMe(txt, id){
var matches = txt.match(new RegExp('<div\\s+id="'+id+'">[\\S\\s]*?<\\/div>'), 'gi');
if(matches) return matches[0].replace(/(<\/?[^>]+>)/gi, '');
return '';
}
var content1 = findMe(res,1);
var content2 = findMe(res,2);
var content3 = findMe(res,3);
var content4 = findMe(res,4);
JSFiddle
As you've tagged your question jquery, I assume this is in a browser context (or some other context with a DOM). If so, the simplest way to is to parse the HTML and use the resulting disconnected DOM tree:
var res = '<div id="1">1</div>' +
'<div id="2">12</div>' +
'<div id="3">123</div>' +
'<div id="4">1234</div>';
var parsed = $(res);
var contentDiv1 = parsed.filter("[id=1]").text(); // See note below
snippet.log("1: " + contentDiv1);
var contentDiv2 = parsed.filter("[id=2]").text(); // See note below
snippet.log("2: " + contentDiv2);
// ...and so on (or use a loop)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Note: Although id value starting with digits are valid HTML, it's awkward to use them because in a CSS id selector (#foo), you can't start the ID value with an unescaped digit (e.g., #1 is an invalid selector). That's why I've had to use the attribute selector [id=1] above. You can work around it with escaping, but by far the best option is just to not start ID values with digits in the first place.