[thelist] Javascript regular expression

Liorean Liorean at user.bip.net
Sun Feb 3 03:16:01 CST 2002


At 23:46 2002-02-02 +0000, Michael Galvin wrote:
>Liorean
>
>Silly q, but why the extra / at the start?  Why not just
>
>\\|etc
>
>I'm a Perl virgin, BTW.  ;)

Oh, that was JavaScript using RegExp, and nothing else.
The answer is simple: When you set a variable to a regular expression, you
can't use "" because then it'd be a string, not a RegExp. So, you use / at
the start and / at the end instead. Also, if you want to search for more
than one occurrence and put them into an array you add a g after the
closing /, and if you want it to be case insensitive, you put an i at the end.

Thus, let me give you some examples:

// This RegExp will find any occurrence of 'mac' in whatever string you're
using it on.
var re=/mac/i;
alert(re.test(navigator.platform)?"You're using a Mac":"You're not using a
Mac");

// This RegExp will find any occurrences of ba in a string.
var re=/ba/g;
var str="abBbaaaBabbbA";
alert(str+":\n\n  "+str.match(re));

// This RegExp will replace all occurrences of Liorean with Big Fat Dork
var re=/Liorean/g;
var str="Liorean said: Hello, good men! You may call me Liorean";
alert(str+":\n\n  "+str.replace(re,"Big Fat Dork"));



So, it's simple the syntax you use to declare a RegExp. For more
information I'd say you better search the JavaScript reference at Netscape
DevEdge.

// Liorean




More information about the thelist mailing list