1295455217_diagram-02
June 2nd, 2011

Javascript Backreferences: String Replace with $1, $2…

Learn how to manipulate string easily using javascript back-references. JavaScript has a regular expression object, RegExp provides group functionality by placing part of a regular expression inside round brackets or parentheses. Groups are more powerful because by default these are captured and stored in array(back reference array) and we can use the array later in regular expression for exact matching. Let us understand this by examples:

Example 1-Change Date Format:

Suppose you want to change MM/dd/yyyy to yyyy-MM-dd format. It’s very easy in javascript using back-references. See following:

document.write(’12/05/2008′.replace(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/g, ‘$3-$1-$2’));

Output:
2008-12-05

In the expression, three groups are defined for Month, Date and Year. These groups values are reordered and joined with dash.

Example 2- Change One tag to another tag:

Suppose we have to replace links to their text in a paragraph means

<a href=”http://www.google.com”>Google</a>
to
<span>Google</span>.

See following code:

var str ='This is <a href=\"http://techbrij.com\">TechBrij</a>, A wonderful collection of resources like <a href="http://www.asp.net">ASP.NET</a> , <a href="http://jquery.com">jQuery</a> blah blah...  ';
 str=str.replace(/(<a href="([^"]+)">([^<]+)<\/a>)/ig,'<span>$3</span>');
alert(str);


javascript backreferences

Output:
This is <span>TechBrij</span>, A wonderful collection of resources like <span>ASP.NET</span> , <span>jQuery</span> blah blah…

Sometimes, Javascript back-references solves complex task in easy way. It is very handy and useful.

Hope, It helps.