Last active
January 5, 2023 02:19
-
-
Save meoow/f3aef00f2805db0cf2e36ce6b7484ebc to your computer and use it in GitHub Desktop.
.interpolate method for formating jscript string
This file contains 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
String.prototype.replSubStr = function(startat, endat, replacement) { | |
return this.substring(0, startat) + replacement + this.substring(endat+1); | |
} | |
String.prototype.interpolate = function() { | |
var str = this.toString(); | |
var dict = new Object(); | |
if (arguments.length) { | |
for(var k=0;k<arguments.length;k++) { | |
if(typeof arguments[k] === "object") { | |
for(var j in arguments[k]) { | |
dict[j] = arguments[k][j]; | |
} | |
} else { | |
dict[k] = arguments[k]; | |
} | |
} | |
} | |
var subs = new Array(); | |
for( var i=0; i<str.length-2;++i) { | |
if(!(str.charAt(i)=='{' && str.charAt(i+1)!='{')){ | |
continue | |
} | |
for(var j=i+1; j<str.length;++j) { | |
if(!(str.charAt(j)=='}' && str.charAt(j+1)!='}')){ | |
continue | |
} | |
token = str.substr(i+1,j-i-1); | |
if (dict[token]!==undefined) { | |
subs.push([i,j, dict[token]]); | |
i = j; | |
} | |
} | |
} | |
while(subs.length){ | |
inst = subs.pop(); | |
str = str.replSubStr(inst[0],inst[1],inst[2]); | |
} | |
return str; | |
} | |
WScript.Echo("{0}! Are you {ok}! {{This}} will be ignored".interpolate('Hello',{'ok':'Okay','This':'That'})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment