How To Capture A String Between Two Tags
Solution 1:
You can just treat the HTML inside of the <p>
tag as a string and then get the substring
between the </label>
and the first <br>
:
var totalText = $("p").html();
//determine start-pos and end-pos of desired substring, and then get itvar startPos = totalText.indexOf("</label>") + "</label>".length;
var endPos = totalText.indexOf("<br");
var targetText = totalText.substring(startPos,endPos).trim();
(fiddle: http://jsfiddle.net/3uw8ux9t/3/)
startPos
finds the position of the first"</label>"
and then adds the length of"</label>"
to that.endPos
finds the position of the first"<br"
(I left the closing>
out because officially it's spelled<br />
, my way allows for both ways of spelling).targetText
finally takes the substring from thestartPos
to theendPos
. (.trim()
removes any empty spaces from the start and end of your new string)console.log(targetText)
gives:Capture me!
UPDATE:
After your comment, I rewrote my script to accommodate for your specified needs:
$(document).ready(function(){
functiongetUnenclosedText(selector,pointer,tag) {
var str = $(selector).html();
//determine start-pos and end-posvar startPos = str.indexOf(pointer+"</"+tag+">") + (pointer+"</"+tag+">").length;
var endPos = str.indexOf("<"+tag,startPos);
//if there are line-breaks, reset end-posif (str.indexOf("<br",startPos)<endPos || endPos==-1) {
endPos = str.indexOf("<br",startPos);
}
//return substringif (endPos==-1) {return str.substring(startPos).trim();} //if it was the last text in the containerelse {return str.substring(startPos,endPos).trim();}
}
console.log(getUnenclosedText("p","item 1","label")); //(selector,pointer,pointerTag)alert('Item 1: '+getUnenclosedText("p","item 1","label") +'\n'+ 'Item 3: '+getUnenclosedText("p","item 3","label"));
});
p {
font-family:arial;
}
label {
display:inline-block;
width:25%;
font-weight:bold;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><p><label>item 1</label> Capture me!
<br /><br /><label>item 2</label> Don't capture me
<label>item 3</label> capture me as well
<br /><br /><label>item 4</label> Don't capture me either
</p>
I tried to make it as scalable as possible, using variables for all the parameters, so that the script is not limited to <p>
and <label>
anymore.
- You now have to call the function
getUnenclosedText(selector,pointer,tag)
, every time you want to extract a piece of text. The three parameters make the function scalable, so you can use it on various elements, not just<label>
in<p>
:"selector"
specifies which container element(s) you want to perform the function on. So if you have multiple<p>
tags with different ID's for example, you can access a specific<p>
tag, using its jQuery selector (e.g."p#someid"
)."pointer"
specifies after which piece of text (e.g."item 1"
,"item 2"
) you want to extract the unenclosed text."tag"
specifies the tag-type that encloses the pointer (e.g."label"
,"span"
).
If you have any questions, just ask them in the comments and I'll answer them or update this answer if need be, but I think you can find most of what you need on the internet.
Read this about how to use indexOf()
, and you'll understand the most difficult parts of the code.
Solution 2:
$('p label:contains("item 1")').prop('nextSibling')
will select that text node after the label.
If you want to style that using css then you'll have to use jQuery to wrap that text in a span and set the css color to red. Either that or color the content on the <p>
tag red and set the color of that label back to it's original color.
Also keep in mind that what you get back from .nextSibling
will be a text node and not a jQuery object.
Solution 3:
You can't get that specific text using only jQuery, because it only deals with elements. The text that you want is between elements, and the parent element contains more text than you want.
You can get the DOM nodes from that label and until the next label, and get the text content from them.
In your example there are two text nodes and two br
elements between the labels, so you would need to decide what you want from the br
elements. In the example I have translated them to line breaks in the text:
var e = $('p label:eq(0)')[0].nextSibling;
var s = '';
while (e.tagName != 'LABEL') {
if (e.tagName == 'BR') {
s += '\n';
} else {
s += e.nodeValue;
}
e = e.nextSibling;
}
console.log(s);
Solution 4:
functioncaptureStr(p, itm) {
if(p.find('label').length > 0 && p.find('label:eq(0)').text().indexOf(itm) >= 0)
return p.html().split("<br>")[0].split("</label>")[1].trim();
}
To test:
console.log(captureStr($('p'), "item 1"));
Capture me!
If you have many of these structure then you can loop through and call the function for each one.
Solution 5:
Assuming the structure doesn't change much from what you posed the following will write the nodes out to the console based on the next sibling not being empty. I think this should work as many labels as you have in any number of paragraph tags. Here is a working JSFiddle (http://jsfiddle.net/RVAProgrammer/jsqxfgxe/)
console.log($('p').contents().filter(function () {
var isTextNode = this.nodeType === Node.TEXT_NODEif (isTextNode) {
if ($(this)[0].nextElementSibling === null) {
returnfalse;
}
returntrue;
}
returnfalse;
}).text());
Post a Comment for "How To Capture A String Between Two Tags"