how to get specific values from string? - javascript

I am getting a variable which value always follows this format:
"<div>
</div>
<div>
<span style="font-family:tahoma,geneva,sans-serif;"><span>VALUE 1</span></span></div>
<div>
<strong><span style="font-family:tahoma,geneva,sans-serif;">VALUE 2</span></strong></div>
<div>
<span style="font-family:tahoma,geneva,sans-serif;"> </span>VALUE 3</div>
"
How can I get VALUE 1, VALUE 2 and VALUE 3 using JavaScript (not jQuery or other libs)?
NB:
in Console, I get those values (I call them b)
typeof(b) returns string

The most simplest way using jQuery.
var a = '<div>\
</div>\
<div>\
<span style="font-family:tahoma,geneva,sans-serif;"><span>VALUE 1</span></span></div>\
<div>\
<strong><span style="font-family:tahoma,geneva,sans-serif;">VALUE 2</span></strong></div>\
<div>\
<span style="font-family:tahoma,geneva,sans-serif;">au </span>VALUE 3</div>'
var HTML = $.parseHTML(a)
var val1 = $(HTML[1]).find('span span').text()
var val2 = $(HTML[2]).find('span').text()
$(HTML[3]).find('span').remove()
var val3 = $(HTML[3]).text()
console.log(val1, val2, val3)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Use Array#map and then Array#filter
innerHTML the string to a temp element and use DOM-api to manipulate data.
Use 'span[style]' selector to get only those span elements having style attribute.
var str = '<div>\
</div>\
<div>\
<span style="font-family:tahoma,geneva,sans-serif;"><span>VALUE 1</span></span>\
</div>\
<div>\
<strong><span style="font-family:tahoma,geneva,sans-serif;">VALUE 2</span></strong></div>\
<div>\
<span style="font-family:tahoma,geneva,sans-serif;">VALUE 3</span></div>';
var div = document.createElement('div');
div.innerHTML = str;
var spanElems = div.querySelectorAll('span[style]');
var spans = [].map.call(spanElems, function(el) {
return el.textContent.trim();
}).filter(Boolean);
console.log(spans);

You can save the string as a variable, and then use htmlString.match(/VALUE \d+/gmi)

Update:
If the input is a valid HTML string you could parse with this trick (not jQuery or other libs):
var your_string = `<div> </div><div><span style="font family:tahoma,geneva,sans-serif;"><span>VALUE 1</span>fgfgfg</span></div><div><strong><span style="font-family:tahoma,geneva,sans-serif;">VALUE 2</span></strong></div><div><span style="font-family:tahoma,geneva,sans-serif;"> </span>VALUE 3</div>`
var obj_evaluator = document.createElement("div");
obj_evaluator.innerHTML = your_string;
// get the list of div
var list_div = obj_evaluator.getElementsByTagName('div');
var value1 = (list_div[1].firstChild.firstChild.textContent); //value 1
var value2 = (list_div[2].firstChild.firstChild.textContent); //value 2
var value3 = (list_div[3].lastChild.textContent); //value 3
// create an array
var result = [value1,value2,value3]
// print result
console.log(result);
Old answer (wrong because of the VALUE 3,but if all the VALUE are inside the 'span' then this is the right answer! ):
var obj_evaluator = document.createElement("div");
obj_evaluator.innerHTML = your_string;
// debug row
console.log(obj_evaluator);
var list_span = obj_evaluator.getElementsByTagName('span');
for (var i = 0; i < list_span.length; i++) {
console.log(list_span[i].innerHTML);
// here you can print other info of the node
}

Related

How can I get the matched element's parent div attribute by regular express using Javascript

Have a html string see below.
<div sentence="11">
<p>
how are you Tom, how are you Tom
</p>
</div>
<div sentence="12">
<p>
how are you Tom
</p>
</div>
When user select the name 'Tom', I will replace the string 'Tom' using a name tag with some html style. The result what I want see below.
<div sentence="11">
<p>
how are you <span class="ano-subject" data-oristr="Tom" data-offset="1" data-sentence="11"><NAME></span>, how are you <span class="ano-subject" data-oristr="Tom" data-offset="2" data-sentence="11"><NAME></span>
</p>
</div>
<div sentence="12">
<p>
how are you <span class="ano-subject" data-oristr="Tom" data-offset="1" data-sentence="12"><NAME></span>
</p>
</div>
I will using the code below to do the replace.
var content = HTML CODE ABOVE;
var selectText = 'Tom';
var regex = new RegExp('(?=\\s|^|\\b)(?:' + selectText + ')(?=\\s|$|\\b)', "g");
var pre_sentence = 0;
var offset = 0;
content = content.replace(regex, function(match, position) {
var curr_sentence = ???; // how can I get this element's parent div attribute 'sentence' ?
if(pre_sentence != cur_sentence){
// this is new sentence.
offset = 1;
pre_sentence = curr_sentence;
} else {
offset++;
}
var replace = '<span class="ano-subject" data-oristr="Tom" data-offset="'+offset+'" data-sentence="'+curr_sentence+'"><NAME></span>';
return replace;
});

How to replace text between tags only

I have multiple h2 tags and every tag contains text and has a custom attribute called data-options. This attribute has multiple options separated by commas and one of these options is the h2 tag text itself.
HTML:
<h3 id='test' data-options='happy,sad,fantastic'>sad</h3>
<h3 id='test2' data-options='1,2,3,4'>3</h3>
jQuery:
var indexArray = ['happy','1'];
$('h3').each(function(i){
var $this = $(this),
value = $this.text(),
code = $('body').html();
code = code.replace(value, indexArray[i]);
$('body').html(code);
});
This is what I expect:
<h3 id='test' data-options='happy,sad,fantastic'>happy</h3>
<h3 id='test2' data-options='1,2,3,4'>1</h3>
Instead I get this:
<h1 id="test" data-options="happy,happy,fantastic">sad</h1>
<h3 id="test2" data-options="1,2,3,4">3</h3>
As you can see the script changes the first text it encounters, not the one inside the tags.
This is a working demo for the script : http://jsfiddle.net/fs1sfztx/
It makes no sense to do a replace unless you're searching. Which means you have to be provided what to search for and what to replace it with. So far only the text to in the h3 is given.
Assuming that each index in indexArray matches the index of each h3 element, then you can compare the current indexArray element indexArray[i] with each of the words in the corresponding elements data-options attribute. When a matches, set the innerText prop to that word.
var indexArray = ['happy','1'];
$('h3').text( function( i, txt ) {
var that = $(this);
var ntxt = txt;
$.each( that.data('options').split(','), function( j, u ) {
indexArray[i] !== u || (ntxt = u);
});
return ntxt;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3 id='test' data-options='happy,sad,fantastic'>sad</h3>
<h3 id='test2' data-options='1,2,3,4'>3</h3>
If all you wanted is to play with the replace method, then you could use something like this:
var indexArray = ['happy','1'];
var allhtml = $('body').html();
$('h3').each( function( i ) {
var txt = $(this).text();
var re = new RegExp( '>' + txt + '<', 'g' );
allhtml = allhtml.replace( re, '>' + indexArray[i] + '<' );
});
$('body').html( allhtml );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3 id='test' data-options='happy,sad,fantastic'>sad</h3>
<h3 id='test2' data-options='1,2,3,4'>3</h3>

Add a span tag to certain characters in a string with javascript/jquery

I have output from a CMS where I need to add a style to a certain character in the string. For instance, my output is:
<div class="date">12 // 14 // 2013</div>
How can I add:
<span style="slashColor">
to the two double slashes so that my result would be:
<div class="date">12 <span class="slashColor">//</span> 14 <span class="slashColor">//</span> 2013</div>
Try this:
var original = $('.date').text();
var new_version = original.split('//').join('<span class="slashColor">//</span>');
$('.date').html(new_version);
Fiddle
If you have many div like the example you posted, you can use this:
$('.date').each(function () {
var original = $(this).text();
var new_version = original.split('//').join('<span class="slashColor">//</span>');
$(this).html(new_version)
});
Fiddle
var elements = document.getElementsByClassName('date');
for (var i = 0, e; e = elements[i++]; ) {
e.innerHTML = e.innerHTML.replace(/\/\//g, '<span class="slashColor">//</span>');
}
or the jQuery way:
$('.date').each(function () {
$(this).html($(this).html().replace(/\/\//g, '<span class="slashColor">//</span>'));
}

How to get the html element from jquery object

I have a html like follows.
<tr class="meta-info" id="${page.id}">
<td>
<div class="pull-left">
<font size="1">
Like
</font>
</div>
<div class="pull-right" style="font-size:1">
<span class="badge"><i class="icon-thumbs-up"></i>1</span>
</div>
</td>
</tr>
I am trying to increase the number of likes when ever the user cliks on Like hyperlink.
Here is my jquery code. I want to know how i can get the html element from the jquery object.
$(".like").click(function(event){
var parentTr = $(event.target).closest("tr");
if(parentTr.length){
var pageId = parentTr.attr("id");
var spanEle = parentTr.get(0)+" div span:first-child"; ------(1)
var lastNumber = parseInt(spanEle.text());
spanEle.text(lastNumber+1);
}
});
I don't know if i am doing right on line which is marked 1.
I think you need to add an extra <span> tag so that you can replace the count without touching the adjacent icon
<span class="badge"><i class="icon-thumbs-up"></i>
<span class="like-count">1</span>
</span>
then you can address it
$(".like").click(function() {
var spanEle = $(this).closest('tr').find('.like-count').first();
if (spanEle.length) {
var newCount = parseInt(spanEle.text());
spanEle.text(newCount + 1);
}
});
In an event handler, the this reference is event.target. You may be able to handle the element doesn't exist case neater than that too but that way's safe.
JSFiddle demo: http://jsfiddle.net/rupw/VfCvK/
Try this...
$(".like").click(function(event) {
var parentTr = $(event.target).closest("tr");
if (parentTr.length) {
var pageId = parentTr.attr("id");
var spanEle = parentTr.first('.badge');
var lastNumber = parseInt(spanEle.text(), 10);
spanEle.text(lastNumber + 1);
}
});
If the span element always has that classname then it will find the first (only?) one and return an int value of the text within.
Try: Fiddle
var lastNumber = parseInt(parentTr.find('.pull-right span').text(), 10);
You code will look like:
$(".like").click(function(event) {
var parentTr = $(event.target).closest("tr");
if (parentTr.length) {
var pageId = parentTr.attr("id");
var spanEle = parentTr.find('.pull-right span');
var lastNumber = parseInt(spanEle.text(), 10);
spanEle.text(lastNumber + 1);
}
});
Update: If you wish to keep the <i> tag then use:
spanEle.html(spanEle.html().replace(lastNumber, lastNumber + 1));
insteadof : spanEle.text(lastNumber + 1);
Sample

Regular expression in javascript to get contents of <span> tags

I have a string with this form
<p>Central: <span class="fieldText">Central_Local</span>
<br>Area Resolutoria: <span class="fieldText">Area_Resolutoria</span>
<br>VPI: <span class="fieldText">VIP</span>
I'm trying to get the span elements, and find the values within
var message = currentMarker.get("mensaje");
var pat = new RegExp("^(.*?<span .*?>(.*?)</span>.*?)+$");
message.match(pat);
I need to get these values:
Central_Local
Area_Resolutoria
VIP
IP_ERX
How can this be done, or how can my regex be improved?
jQuery
var message = currentMarker.get("mensaje");
var contents = [];
$('<div>', {html: message }).find('span.fieldText').each(function(){
contents.push( $(this).text() );
});
demo at http://jsfiddle.net/DfDPR/2/
Pure javascript
var message = currentMarker.get("mensaje");
var contents = [];
var div = document.createElement('div');
div.innerHTML = message;
var spans = div.getElementsByTagName('span');
for (var span = 0; span < spans.length; span++)
{
contents.push(spans[span].innerHTML);
}
demo at http://jsfiddle.net/DfDPR/3/
As mentioned in the comments, regex is not a good candidate for parsing HTML...
Trivial task in jQuery:
var values = $('span.fieldText', message).map(function(){
return $(this).text();
}).get();
values will be an array with all the values you need. You can iterate over it or do anything you like.

Categories

Resources