Skip to content

Instantly share code, notes, and snippets.

@Lcfvs
Created May 3, 2016 14:26
Show Gist options
  • Select an option

  • Save Lcfvs/56184afb8dbe1fdd4f6dcb4fe1b653b1 to your computer and use it in GitHub Desktop.

Select an option

Save Lcfvs/56184afb8dbe1fdd4f6dcb4fe1b653b1 to your computer and use it in GitHub Desktop.
Simple & controlled template string emulation
/**
* @module: string-inject
* @version: 1.0.0
* @author: Lcf.vs
* @copyright: © 2015
* @license: MIT
* @exports: {function} inject(name, str, data)
* @description: Injects some map-based data into a string
* @param: {string} name
* @description: The map name
* @param: {string} str
* @description: The string which needs to be rewritten
* @param: {object} map
* @description: The data to inject
* @return: {string}
* @description: The rewritten string
*/
'use strict';
const ADD_SLASH_PATTERN = /\\/g;
const MAP_PATTERN = /(\$\{)(\w+)/g;
var inject;
inject = function({
name: name,
map: map,
str: str,
global: global,
require: require,
module: module,
exports: exports,
__dirname: __dirname,
__filename: __filename,
define: define
}) {
var sanitized;
sanitized = str
.replace(ADD_SLASH_PATTERN, '\\\\')
.replace(MAP_PATTERN, function(match, prefix, suffix) {
if (suffix === name) {
return prefix + suffix;
}
return '\\' + prefix + suffix;
});
sanitized = 'return function() {return ' + sanitized + ';}();';
return Function(
name,
'ADD_SLASH_PATTERN',
'MAP_PATTERN',
'inject',
'sanitized',
'name',
'str',
`return \`${sanitized}\`;`
).call(null, map);
};
module.exports = inject;
@Lcfvs
Copy link
Author

Lcfvs commented May 3, 2016

Usage :

inject({
    name: 'map',
    map: {
        property: 'value'
    },
    str: 'The property value is "${map.property}"'
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment