In PHP, there are a few ways in which you can specify a string which, if it contains a variable name, the corresponding value will replace it. This process is referred to as string expansion and is talked about here on Unfortunately, there is no real way to implement this in JavaScript so that it will work based on the scope you are in (at least not with a function), but we can fake it a bit so it will read from the global scope. The following is a simple function definition for this:

(function(global, nil) {
  String.prototype.expand = function(context, blankIfNotIn) {
    context = context == nil ? global : context;
    return this.replace(/\{([A-Z_$][\w$]*)\}/gi, function(all, name) {
      return (name in context)
        ? context[name]
        : (blankIfNotIn ? "" : all);


This function will expand all variable names surrounded by a set of curly braces into the value of each variable. Only standard variable names will be expanded. Standard variable names are at least one character long, start with a letter, dollar sign ($), or underscore (_), and contains only letters, numbers, dollar signs ($), and underscores (_).


  1. context
    The object to be searched for the specified variable name. This parameter is optional and defaults to the global object.
  2. blankIfNotIn
    Boolean value, if this evaluates to true, indicating that if the variable name specified isn’t found within the context object, then empty string should replace the variable name placeholder. If this evaluates to false and the variable name specified isn’t found within the context object, the placeholder will remain as is. This parameter is optional and defaults to false.


The original string with all of the variable name placeholders that could be resolved, replaced with the correspond values found in the context object.


Now let’s look at an example of calling this function to get what you want.

When you try the above code out you will see that this code will actually fill the first and last names specified into the welcome message that is displayed. Of course, the downside to this is the fact that you have to pollute the global namespace in order to use this function without any parameters. If you want to go a different route and not pollute the global namespace, you can use code like the following:

Now we are using a function and now none of the string variables are kept in the global context. Although this function can’t read from the current context (unless the context is the global one), this function is still pretty useful. It may not be PHP, but it doesn’t have to be because it is the excellent scripting language known as JavaScript. šŸ˜Ž

Leave a Reply

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