Split words, characters, lines

/**
* 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>");
}

Usage

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>"

The usage is pretty simple. Just pass in the string to wrap as first argument. If you need custom markup, pass it in as the second argument, while $& is replaced by each char/word/line.

https://stackoverflow.com/questions/8609170/how-to-wrap-each-word-of-an-element-in-a-span-tag

Accessibility

CSS IRL had some accessibility concerns with split text since it is generating a lot of extra HTML elements.

https://css-irl.info/how-to-accessibly-split-text/

<h1 aria-label="Oh hello there">
<span aria-hidden="true">O</span>
<span aria-hidden="true">h</span>
<span aria-hidden="true"> </span>
<span aria-hidden="true">H</span>
<span aria-hidden="true">e</span>
<span aria-hidden="true">l</span>
...
</h1>

Let me know what you think on twitter @rdallaire

← Return to blog