Last active
March 29, 2016 08:45
-
-
Save junpluse/3560742ade9b4f6b09d2 to your computer and use it in GitHub Desktop.
Format multi-line text for ES5
This file contains hidden or 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
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<meta name="viewport" content="width=device-width"> | |
<title>Multiline Text Formatter for ES5</title> | |
<style> | |
body { | |
margin: 24px; | |
font-family: sans-serif; | |
background: #fff; | |
} | |
main { | |
display: block; | |
max-width: 800px; | |
margin: auto; | |
} | |
textarea { | |
display: block; | |
width: calc(100% - 8px * 2); | |
height: 160px; | |
margin: 24px 0; | |
padding: 8px; | |
font-family: monospace; | |
font-size: 1.1rem; | |
border: 1px solid #ccc; | |
border-radius: 4px; | |
} | |
#output { | |
display: none; | |
} | |
</style> | |
</head> | |
<body> | |
<main> | |
<h1>Multiline Text Formatter for ES5</h1> | |
<textarea id="input" placeholder="Paste multiline text here"></textarea> | |
<textarea id="output"></textarea> | |
<p>In ES6, you can use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals">template literals</a> for multiline text.</p> | |
</main> | |
<script> | |
var input = document.getElementById('input') | |
var output = document.getElementById('output') | |
function convert (text) { | |
return 'var string = [\n' + text.split('\n').map(function (line) { | |
return ' \'' + line + '\',' | |
}).join('\n').slice(0, -1) + '\n].join(\'\\n\')' | |
} | |
input.addEventListener('input', function (e) { | |
var text = input.value | |
if (text) { | |
output.value = convert(text) | |
output.style.display = 'block' | |
} | |
else { | |
output.value = '' | |
output.style.display = 'none' | |
} | |
}) | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment