Last active
August 29, 2015 14:23
-
-
Save djalmajr/61d8add96e7fc2825325 to your computer and use it in GitHub Desktop.
Surround letters, words and lines with span
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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>" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment