你不需要 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