2

I am trying to reformat the following text using jquery:

<a href="3.3/">3.3/</a>                                               14-Apr-2011 14:43                   -
<a href="3.4.2/">3.4.2/</a>                                             06-Jun-2011 11:20                   -
<a href="3.8/">3.8/</a>                                               01-Jun-2011 16:27                   -

I am wrapping the links with li tags no problem there, but trying to extract the date and get rid of the rest of the text cruft is hurting my brain. I have looked a the jQuery text selectors but nothing seems to be popping up for me suggestions?

In an ideal world I would have something like this at the end of the day:

<li><a href="3.3/">3.3/</a><br><p>14-Apr-2011 14:43</p></li>
bmartinek
  • 568
  • 2
  • 6
  • 17
  • 1
    The answer to [this question](http://stackoverflow.com/questions/298750/how-do-i-select-text-nodes-with-jquery) may be helpful – Michael Mior Sep 01 '11 at 04:31
  • Thanks that did help me isolate the first part which was helpful I used the remove method after to strip it away for initial purposes. Oddly iOS was not so pro on the filtering. – bmartinek Sep 02 '11 at 05:34
  • Interesting. I've never tried that technique before so it's good to know. – Michael Mior Sep 02 '11 at 14:28

1 Answers1

0

Since you want to isolate definable patterns in your content I would use regular expressions to parse out the data you're looking for then reformat that data as needed. Here is a basic example:

$(document).ready(function () {
    var input = $('#content').html();           // Get content from #content container
    var regex = /^(<a.+<\/a>)\s+(\S+)/gm;       // Setup regex to extract anchor & date

    // Execute regex against input and return subpattern matches
    while( result = regex.exec(input) )
    {
        // Add formatted output to <ul>
        $('ul').append("<li>" + result[1] + "<br><p>" + result[2] + "</p></li>");
    }
});

This example assumes that your input string is inside the element #content and that you want to append your newly created <li>'s to <ul>, which may not be the case. However, both assumptions should be easy for you to adapt to your needs.

Joe Landsman
  • 2,177
  • 13
  • 9
  • Wow, looks pretty good. What does the "gm" part do in the regex var? – bmartinek Sep 02 '11 at 05:35
  • Those are called "flags". They dictate certain characteristics of the search. You can find definitions at http://www.javascriptkit.com/javatutors/redev.shtml. Basically, the "g" flag tells the processor to search for all matches in the string and "m" tells the processor there are multiple lines in the string. The latter is important when you want to use the "^" and "$" anchors to match individual lines in a block of content. – Joe Landsman Sep 02 '11 at 15:13