JSFiddle - React, Tailwind, and code Playground
by jrunning
HTML
<pre id="out"></pre>
JavaScript
// http://stackoverflow.com/a/33772348/179125
function zigzag(word, numLines) {
var mod = 2 * numLines - 2;
var maxIdx = numLines - 1;
var lines = new Array(numLines);
// initialize array with empty strings
for (var i = 0; i < numLines; i++) {
lines[i] = '';
}
// for each letter...
for (var i = 0; i < word.length; i++) {
// calculate which line it goes on
var lineNo = maxIdx - Math.abs(i % mod - maxIdx);
// iterate over the lines
for (var j = 0; j < numLines; j++) {
// if this is the line the letter should go on, append it
if (j === lineNo) {
lines[j] += word[i];
continue;
}
// otherwise append '.'
lines[j] += '.';
}
}
return lines.join('\n');
}
var word = 'defendtheeastwallofthecastle';
document.getElementById('out').innerText = zigzag(word, 4);