你不需要 jQuery的这个简单的任务。 String.prototype.replace
和正则表达式应该做的伎俩。
我只是做了一些简单实用的功能,它包装的字母,单词和行:
/**
* Wraps a string around each character/letter
*
* @param {string} str The string to transform
* @param {string} tmpl Template that gets interpolated
* @returns {string} The given input as splitted by chars/letters
*/
function wrapChars(str, tmpl) {
return str.replace(/\w/g, tmpl || "<span>$&</span>");
}
/**
* Wraps a string around each word
*
* @param {string} str The string to transform
* @param {string} tmpl Template that gets interpolated
* @returns {string} The given input splitted by words
*/
function wrapWords(str, tmpl) {
return str.replace(/\w+/g, tmpl || "<span>$&</span>");
}
/**
* Wraps a string around each line
*
* @param {string} str The string to transform
* @param {string} tmpl Template that gets interpolated
* @returns {string} The given input splitted by lines
*/
function wrapLines(str, tmpl) {
return str.replace(/.+$/gm, tmpl || "<span>$&</span>");
}
的使用是非常简单的。只需传入字符串以包装为第一个参数即可。如果您需要自定义标记,请将其作为第二个参数传入,而$&
由每个字符/字/行代替。
var str = "Foo isn't equal\nto bar.";
wrapChars(str); // => "<span>F</span><span>o</span><span>o</span> <span>i</span><span>s</span><span>n</span>'<span>t</span> <span>e</span><span>q</span><span>u</span><span>a</span><span>l</span> <span>t</span><span>o</span> <span>b</span><span>a</span><span>r</span>."
wrapWords(str); // => "<span>Foo</span> <span>isn</span>'<span>t</span> <span>equal</span> <span>to</span> <span>bar</span>."
wrapLines(str); // => "<span>Foo isn't equal</span> <span>to bar.</span>"
你可能想看看[Lettering](http://letteringjs.com/)插件。 – Pointy 2011-12-22 20:10:30
期望的输出是什么? – SpoonNZ 2011-12-22 20:11:11
试着通过举例说明你想要改进你的问题。一个更好的问题名称似乎是'如何包裹每个单词**的span标签中的元素?' – Richard 2011-12-22 20:23:24