text2jsvar is a lightweight JavaScript library for converting plain text to JS string variable.
It can easily transfer the following JavaScript function text into a JavaScript string variable.
Convert:
var sayHello = function() {
alert("Hello World");
}
To:
var result = "var sayHello = function() {\n alert(\"Hello World\");\n}"
Online demo: Text to JS variable converter.
npm install text2jsvar
var text2jsvar = require('text2jsvar');
text2jsvar.convert('a\nb'); // return 'a\\nb'
You can find the minified JS file for browsers at ~/node_modules/text2jsvar/min/text2jsvar.min.js
. Copy this file to your web project and include it using <script>
tag, it will declare a global variable: text2jsvar
.
<script src="text2jsvar.min.js"></script>
<script>
text2jsvar.convert('a\nb'); // return 'a\\nb'
</script>
Description: Convert text to JavaScript string variable.
Parameter | Type | Description |
---|---|---|
source | String | The source string to be converted. |
double | Boolean | Default: false. If double is set to true, the source string will be converted twice. |
The converted text.
Description: Revert the converted text to the source string.
Parameter | Type | Description |
---|---|---|
convertedText | String | The converted text to be reverted back. |
double | Boolean | Default: false. Set double to true if the text was converted twice. |
The source string of the converted text.