Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // This is the Interpol, I use it to make Text Interpolation in Javascript
- // using #{this_format} ...Ruby's Way
- var Interpol = function (text, par, fun) {
- text = text || "";
- par = par || {};
- fun = fun || function(x){ return x };
- return text.replace(/#{[^\}]+}/g, function(m, p, ft){
- var rt = m.substr(2);
- rt = rt.substr(0, rt.length - 1);
- rt = par[rt].toString() || "";
- return fun(rt);
- })
- };
- // And this is how I use it
- // Parameters: [Text], [Things to interpolate], [cool function]
- var text1 = Interpol("Hello, I'm #{name} #{last}", {name: "Herson", last: "salinas"});
- var text2 = Interpol("Hello, I'm #{name} #{last}", {name: "Herson", last: "salinas"}, function(x){
- return x.toUpperCase();
- });
- console.log(text1);
- console.log(text2);
- var sqlParse = function (str) {
- return str.replace(/\\/g, "\\\\").replace(/'/g, "''");
- }
- var query = "select * from users where username = '#{name}' and password = md5('#{pass}')";
- var sql = Interpol(query, {name: "Bobby", pass: "I'm the Fisher"}, sqlParse);
- console.log(sql);
Add Comment
Please, Sign In to add comment