Can jquery functions be used to easily convert a string to a tree, manipulate a node, and convert back into a string?
original question: How are jquery functions like selector and .html() used for string manipulation?
Updates:
- I found related information at this question parse html string with jquery
- Ben Alman has an example of replaceText as a jquery addon which walks the tree and replaces text
- additional insight from this question and answer for how to convert jquery objects to strings
First can jquery be used for the following? (I'll verify in a moment)
var b = $('<a href="#">bacon</a>').html();
does b === 'bacon', the answer is yes.
How can jQuery be used to perform string manipulation: (modified from a sample highlighting answer)
var key = 'bacon';
var str = '<a href="#">bacon</a><a href="#">tastes great</a>';
$(str).contents().each(function() {
var node = this;
if (node.nodeType == 3) {
var text = node.nodeValue;
text = text.replace(new RegExp(key, "g"),
'<span class="Someclass">'+key+'</span>'
));
//replace existing node value with text
});
// convert tree into string
the desired output is a string with the modified element(s):
str = '<a href="#"><span class="Someclass">bacon</span</a><a href="#">tastes great</a>';