Using Javascript, I want to take the content of a string and wrap every single word with a set of <span> tags. Each span tag will have a unique ID attribute that I’ll generate. If a word is already encased in a span tag with an id, leave it alone. If it has a span tag without an id, I need to put an id in the span.
So, the following:
this is <b>a</b> <span>bunch</span> of <span id="aopksd"><i>text</i></span>
Becomes:
<span id="dwdkwkd">this</span> <span id="zdkdokw">is</span> <span id="rrrsass"><b>a</b></span> <span id="lwokdw">bunch</span> <span id="poeokf">of</span> <span id="aopksd"><i>text</i></span>
Ideas on the best way to accomplish this? I’m doing it server-side in node.js. I prefer a non-jquery method.
EDIT:
The id is something I will generate on the server. I just used placeholder fake ids for now. I will use my own globally unique id.
You can try this, but you might have to inspect the parameter a if you want to make a special treatment for your word already in html tag :
live demo : http://jsfiddle.net/NtNtj/
EDIT: If you don’t want to overwrite existing ID, you can try this
http://jsfiddle.net/NtNtj/8/
EDIT: If you can have multiple word in a tag like and you still want to wrap each word in between, you can call recursively the replace function with the value inside the tag as so :
live demo: http://jsfiddle.net/francisfortier/NtNtj/9/