Replace All using JQuery and Regex

24 / Aug / 2012 by Gaurav Sharma 3 comments

I recently found out that use of Regex with jQuery and replace function can turn out to be a very powerful tool for replacing/loading data in html dynamically

The use of replace is made like

var a = "Some text here text";
a=a.replace(/text/g,"one")

This will replace all “text” with “one”

Now imagine how good it would be if we could replace the part of html like “##title##” with a title’s value in a JSON.
We would be able to replace/load an entire html code dynamically by merely sending a JSON (or a list of JSON) that would replace the content of HTML in javascript.

Let us consider that we have a html code which is somethinng like:

<a title='##title##' onclick='showRecipeDetail(\"##friendlyUrl##\", this)'> <img src=\"##imageUrl##\" height='75' width='75' /><div class='recipeTitle'>##title##</div></a>

And we want to load this html with JSON content:

{{title:"abc", friendlyUrl:"xyz", imageUrl:"123"},{title:"pqr", friendlyUrl:"stu", imageUrl:"456"}}

What we will do is that we will identified the values to be replaced by using regex and then replaced all of them using replace function. For eg.:

var data= [{title:"abc", friendlyUrl:"xyz", imageUrl:"123"},{title:"pqr", friendlyUrl:"stu", imageUrl:"456"}]
var HTML_Template = "<a title='##title##' onclick='showRecipeDetail(\"##friendlyUrl##\", this)'> <img src=\"##imageUrl##\" height='75' width='75' /><div class='recipeTitle'>##title##</div></a>";
jQuery(data).each(function(index, recipe) {
			var html = HTML_Template;
			jQuery.each(recipe, function(key, value){
				var regExp = new RegExp("##" + key + "##", 'g');
				html = html.replace(regExp, value)
			});
        });

And hence we will have a our html replaced by merely few line of javascript code and a list of JSON (which we might be getting from ajax responce).

Hope this blog was helpful to you.. :)

Thanks and Regard,
Gaurav Sharma
(gauravs@intelligrape.com)

FOUND THIS USEFUL? SHARE IT

comments (3)

  1. Gaurav Sharma

    Hi harsha,
    You are right. Thanks for pointing the mistake out. I must have been lost in some thoughts while writing the blog.

    Reply

Leave a comment -