views:

37

answers:

2

I have a string of raw text which looks something like this:

1 . . 3 . 4 . | A . A . N . | 1 . 1 . . .

I sadly cannot access the source code, but need to add a span with a class to each of those characters, so that the outputted HTML would look something like this:

<span class="1">1</span> . . <span class="3">3</span> . <span class="4">4</span> . <span class="divider">|</span>

What would be the best way to do that using jQuery?

A: 

you need String.replace

html = str.replace(/[^.]/g, 
     function($0) { return "<span class='" + $0 + "'>" + $0 + "</span>" })

in response to the comment

$(function() {
   var s = $(yourdiv).html();
   s = s.replace(/[^.]/g, function($0) { replacement code });
   $(yourdiv).html(s);
});

this reads html from the div, performs the replace operation and put html back to the document.

stereofrog
Could you just clarify how this would be used in practice? Is it as simple as calling this in a script tag and letting it do it's magic? How would I target a specific element upon which to perform the string replacement?
StuartF
it's not obvious from your question where the source string is coming from and how you're using the new, replaced, string. Can you post more details?
stereofrog
I'll have a div with a unique ID upon which I'll have to perform the string.replace. The text will be there in the document when it loads, and at that point I'll need to perform the replacement in order to be able to apply CSS styling to the individual characters within the string.
StuartF
@StuartF see edit
stereofrog
+1  A: 
container.innerHTML = container.innerHTML.
    replace(/\d+/g, '<span class="$1">$1</span>').
    replace(/\|/g, '<span class="divider">|</span>');
Delan Azabani