Javascript: How Can I Wrap Every Word In A String With A Span Tag Containing A Unique Id?
Using Javascript, I want to take the content of a string and wrap every single word with a set of tags. Each span tag will have a unique ID attribute that I'll generat
Solution 1:
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/
Post a Comment for "Javascript: How Can I Wrap Every Word In A String With A Span Tag Containing A Unique Id?"