且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JavaScript:如何使用包含唯一 id 的 span 标签将每个单词包装在字符串中?

更新时间:2023-02-19 16:20:12

你可以试试这个,但如果你想对已经在 html 标签中的单词进行特殊处理,你可能需要检查参数 a :

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);

现场演示:http://jsfiddle.net/NtNtj/

如果你不想覆盖现有的 ID,你可以试试这个

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);

http://jsfiddle.net/NtNtj/8/

如果您可以在一个标签中包含多个单词,并且您仍然希望将每个单词包装在它们之间,您可以使用标签内的值递归调用替换函数,如下所示:

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);

现场演示:http://jsfiddle.net/francisfortier/NtNtj/9/