Parametrize Strings In Java Script

We have lots of utilities in Many Languages which can spit parametrized text. But in Javascript we dont find any such utilities. Here is one of the useful function which can do this.

Lets say We want to say Welcome Message to User and Based on User Name we want to show a warning message that account expires. Then we create a placeholder in Welcome String for user name and For nUmber of days. here is how we do in Javascript

var welcomeString = “Welcome $1. We would like to inform you that your account exipers in $2 days”;

We now use it like this
Final String would be

jstrprintf(welcomeString,”Ashwin”,1000);
This will print
Welcome Ashwin. We would like to inform you that your account exipers in 1000 days


function jstrprintf() {
len = arguments.length;
if (len == 0) { return; }
if (len == 1) { return arguments[0]; }

var result;
var regexstr;
var replstr;
var formatstr;
var re;

result = "";
regexstr = "";
replstr = "";
formatstr = arguments[0];

for (var i=1; i<arguments.length; i++) {
replstr += String(i+100) + arguments[i] + String(i + 100);
regexstr += String(i+100) + "(.*)" + String(i+100);
}
re = new RegExp(regexstr);
var result;
result = replstr.replace(re, formatstr);
return result;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s