-1

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:

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>';
Community
  • 1
  • 1
Mark Essel
  • 4,606
  • 2
  • 29
  • 47
  • 3
    I cast a rare downvote for this question, and I'd like to explain why. For your first example, you asked "does b === 'bacon'". You've already typed out the code - didn't you try it? A good question, I think, shows that you've done some work and explains your results thus far. That way, when someone finds it by search, they can learn something even from the question, and learn more from the answers. I don't mean to offend, and I hope that you see my point and grow more determined to keep the content on SO really great. – Nathan Long Feb 01 '11 at 13:51
  • `innerHTML` is a browser feature, not a jQuery feature, and it is a String, not a Function. – Quentin Feb 01 '11 at 16:19
  • cleaned up the question, was mangling my browser htmls with jquery's html method – Mark Essel Feb 04 '11 at 14:30
  • Down vote understood Nathan, certainly if they make for better questions here. I'll continue to edit the question. – Mark Essel Feb 04 '11 at 14:52

4 Answers4

2

Yes, but you want .html() instead:

var b = $('<a href="#">bacon</a>').html();
// Or,
var b = $('<a href="#">bacon</a>')[0].innerHTML;

As for the second example:

$('<a href="#">bacon</a>').html(function (i, oldHtml) {
    return oldHtml.replace(/(bacon)/g, '<span class="SomeClass">$1</span>');
});
David Tang
  • 92,262
  • 30
  • 167
  • 149
  • I'd like to match to all text that's not in a tag. here's the fiddle I'm playing with http://jsfiddle.net/victusfate/uVczc/ – Mark Essel Feb 01 '11 at 14:09
  • 1
    Matching all text is different: `$(str).contents().each(function () {if (this.nodeType==3) $(this).wrap('');});` – David Tang Feb 01 '11 at 14:12
  • 1
    @Mark, and there are a few things wrong with your jsfiddle. 1: Don't use document.write in conjunction with document.ready (which jsfiddle does automatically). Instead use `$('
    ' + str + '
    ').appendTo('body')`. 2: CSS uses `:`, not `=`. 3: You need to retrieve the value after `.html(function () ...)` with another `.html()`, e.g. `str = $(str).html(function () ...).html()`.
    – David Tang Feb 01 '11 at 14:21
  • thanks, was fiddling with the css (poor memory for syntax). will swap the writes, and that last hint is much appreciated-> there can be several html elements in the strings I'm working with. also my fiddle jumped to /1 with an update, gotta reset that as the base version (still getting used to it) – Mark Essel Feb 01 '11 at 14:30
2

I would say "not exactly." The specific change that you're trying to make can be done as Box9 shows, but in terms of semantics, I'd say that you don't use jQuery for string manipulation, as far as I'm aware.

jQuery can be used to read and modify the DOM, and exists partly to make that process standard across browsers.

Once you've read the DOM, but before you update it, the part where you parse and change it can be done by manipulating strings, but the actual string manipulation will be in plain Javascript.

Nathan Long
  • 122,748
  • 97
  • 336
  • 451
1

I have read this question and the corresponding comments & links a couple of times now and I am still not sure what the actual question is but...

Can jquery functions be used to easily convert a string to a tree, manipulate a node, and convert back into a string?

Yes.

The trick is using a wrapper element, and the jQuery html() and text() methods. Here is a fiddle to show you what I mean.

Sometimes, you want to use text, to get all the text in an element without grabbing all the child elements like wrapping <b> or <i> tags. After it's a dom element you can use dom manipulation to append, add classes, modify attributes, and all that kind of stuff before casting it back into a string.

Is that the answer you were looking for?

EDIT: Doh! Got answered while I was typing

BigAB
  • 170
  • 5
  • If you're answer has less requirements I'll certainly pick it. I had imagined this type of manipulation would be a one or two liner without additional plugins. I was wrong. Noticed some issues with the solution I came up with. – Mark Essel Feb 05 '11 at 10:07
  • To clarify I'm looking for specific text keys within html data that exists in a string format. Your fiddle accessed data from someClass and added an additional class, not quite what I needed. – Mark Essel Feb 05 '11 at 21:49
0

Got it working using Ben Alman's replaceText and a object to html string converter hack

function one() {
    var key = 'bacon';
    var str = '<a href="#">bacon nation</a> <a href="#">tastes good</a>';
    dump("before str contents: " + str);
    str = $(str).replaceText(new RegExp(key,"gi"),'<span class="SomeClass">' + key + '</span>');
    str = $('<div>').append($(str).clone()).remove().html();
    dump("after str contents: " + str);
}

and the desired output:

<a href="#"><span class="SomeClass">bacon</span> nation</a><a href="#">tastes good</a>

I've included the main calling html + script for completeness

    <style type="text/css"> .SomeClass { background-color: yellow } </style>
    <script type="text/javascript">
        function dump(str) {
            $('<div>' + str + '<br/></div>').appendTo('body');
        }
    </script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
    <script type="text/javascript" src="jquery.ba-replacetext.js"></script>
    <script type="text/javascript" src="test.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            one();
        });
    </script>
Community
  • 1
  • 1
Mark Essel
  • 4,606
  • 2
  • 29
  • 47