Sometimes I want to be able to write code like the following so that I can substitute a placeholder for a given substring:

// Hello {identity}!!!
alert("Hello $1!!!".subIn(prompt("Name:", "world")));

// Did you know that PI is equal to 3.141592653589793?
alert("Did you know that PI is equal to $1?".subIn(Math.PI));

// {a} + {b} = {sum}
// {a} × {b} = {prod}
var a = parseInt(Math.random() * 100),
    b = parseInt(Math.random() * 100);
alert("$1 + $2 = $3\n$1 × $2 = $4".subIn(a, b, a + b, a * b));

In order to get the above code to work, I wrote the following function:

// By Chris West - MIT Licensed
String.prototype.subIn = function() {
  var realArgs = [], 0),
      args = [this].concat(realArgs),
      re = args.slice(0);
  for(var arrIsFn = [], len = re.length, i = 0; i < len; i++) {
    re[i] = len - i - 1;
    arrIsFn[i] = {}[i]) == "[object Function]";
  return this.replace(
    new RegExp("\\$(" + re.join("|") + ")", "g"),
    function(all, num, pos, original) {
      return arrIsFn[num]
        ? args[num](all, pos, original, realArgs)
        : args[num];

This function will take an arbitrary amount of arguments and return the string with all of the matched placeholders with the specified substrings. If a function is passed as a argument, the function will be executed to generate the substring that will be put in the place of the placeholder. In this case, the parameters passed to this callback function will be the placeholder, the position of the placeholder, the original string, and all of the arguments as an array.

Believe it or not, the next version of jPaq is still in the works and I do have plans to put a similar function in the library. In the meantime, I am happy to provide everyone with this function. 8)

Categories: BlogJavaScriptJScript

1 Comment

Bhuvanakalyanaraman · December 15, 2012 at 12:01 PM

I want to know codes in java script for complementary of numbers between 1 to 100

Leave a Reply

Your email address will not be published. Required fields are marked *