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 :
var str = "Bonjour, je m'appelle Francis et je suis le plus bel homme du monde";
var regex = /\S+/g;
var id = 0;
var result = str.replace(regex, function(a) {
return "<span id=" + (++id) + ">" + a + "</span>";
});
alert(result);
live demo : http://jsfiddle.net/NtNtj/
EDIT: If you don't want to overwrite existing ID, you can try this
var str = "Bonjour, je m'appelle <b>Francis</b> et <span id=\"existing\">je</span> suis le plus bel homme du monde";
var regex = /(<.+?<\/.+?>|\S+)/g;
var id = 0;
var result = str.replace(regex, function(a) {
var m = (/<(\w+)([^>]*)>([^<]*)<\/\w+>/).exec(a);
if (m !== null && m[1] === "span" && m[2].test(/id=/))
return a;
return "<span id=" + (++id) + ">" + a + "</span>";
});
console.log(result);
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 :
var str = "Bonjour, <b>je m'appelle Francis</b> et <span id=\"existing\">je</span> suis le plus bel homme du monde";
var regex = /(<.+?<\/.+?>|\S+)/g;
var id = 0;
var result = str.replace(regex, function(a) {
var m = (/<(\w+)([^>]*)>([^<]*)<\/\w+>/).exec(a);
if (m !== null && m[1] === "span" && m[2].test(/id=/))
return a;
if (m !== null)
return "<" + m[1] + m[2] + ">" + m[3].replace(regex, arguments.callee) + "</" + m[1] + ">";
return "<span id=" + (++id) + ">" + a + "</span>";
});
console.log(result);
live demo: http://jsfiddle.net/francisfortier/NtNtj/9/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.