Free Online Regular Expressions Testing Tool

I wanted to use something like String.Format but in the ASP with JScript code world...

First I tried:

var str = "asdhkjahk {0} asdkj askldj l {0}";
str = str.replace("{0}", "BCoelho2000");

// output: "asdhkjahk BCoelho2000 asdkj askldj l {0}"

I almost did it! But a {0} token that wasn't replaced.

If only I could replace all matches of my pattern.

Here's how I did it:

The second thing that came to my mind was: regular expressions.

With regular expressions you can specify that you want a global search of your pattern.

So I modified my code to:

var str = "asdhkjahk {0} asdkj askldj l {0}";
str = str.replace(new RegExp("{0}", "g"), "BCoelho2000");

// output: "asdhkjahk {BCoelho2000} asdkj askldj l {BCoelho2000}"

Notice the second parameter of the RegExp constructor: "g". With the g parameter I'm instructing the RegExp that I want to perform a global search.

You must remember that in the regular expressions world some characters have special meaning. You could have a look into a regular expression reference sheet for a complete list.

So I just need to remove the characters { and } from the string. Here's the final code:

var str = "asdhkjahk {0} asdkj askldj l {0}";
str = str.replace(new RegExp("(\\{0\\})", "g"), "BCoelho2000");

// output: "asdhkjahk BCoelho2000 asdkj askldj l BCoelho2000"

The \\ will be replaced by the JavaScript script engine by \. So I'm saying that I want to replace the group {0}.

I couldn't do all of this in a acceptable time without a great free online regular expression testing tool.

And I happened to know one: RegExr.

RegExr shows you in real time how your regular expression will behave and what tokens it will find.

It also provides you with an in depth list of regular expression rules and patterns that you can use.

RegExr also exists in the desktop world.

What tools do you use for testing you Regular Expressions?

P.S: I just found a cool article that shows you how you can use String.Format in the Javascript World.

Reblog this post [with Zemanta]

Be a part of our private list!

Enter your e-mail and access The Rabbit Way's exclusive offers.

Enter your Email

Preview | Powered by FeedBlitz

Or read this related articles

Widget by Hoctro | Jack Book

No comments:

Post a Comment