regular expressions in JavaScript problems
mintymoke
Status: New User - Welcome
Joined: 27 Nov 2007
Posts: 1
Reply Quote
Hi there,

I'm frustrated! I am trying to get what I think should be a simple regular expression working, but it's evading me. In perl it would be

:: Code ::
if ($myString ~= m/\,/) {do what I tell you!}


in javascript from what I have read match() seems to be the method I need. All I need to do is check for the existance of a comma in a string so I can deal with the string as an array.

:: Code ::
var myString = "blah,blah,blah";
if (myString.match(/,/)) {alert("this is an array!");}


this returns myString.match() is not a function

so I tried

:: Code ::
var re = new RegExp(/,/);
if (myString.match(re)) {alert("this is an array!");}


same error

I know that it's probably something really simple so apologies. I'm only testing in Firefox at present.

thanks

A
Back to top
jeffd
Status: Assistant
Joined: 04 Oct 2003
Posts: 594
Reply Quote
I have no idea why match would show as not a function on your browser, however, but this information might help.

You don't need to use new regEx at all, not sure where that idea came from.

match() works like this: it returns an array of strings that matched the regex pattern.

:: Quote ::
The match() method takes a regular expression as a parameter and returns an array of all the matching strings found in the string given. If no matches are found, then match() returns false.

So to use match(), you do this - note that to use regex, no ' or " can be used when constructing the regex pattern:

:: Code ::
var myString = "blah,blah,blah";
if (myString.match(','))
{
   alert("this is an array!");
}
else
{
   alert("this is not an array!");
}

Or, with normal regex:
:: Code ::
var myString = "blah,blah,blah";
regEx=/,/;
if (myString.match(regEx))
{
   alert("this is an array!");
}
else
{
   alert("this is not an array!");
}

You can also use, with a different test syntax, indexOf() (or here)

:: Code ::
var myString = "blah,blah,blah";
if (myString.indexOf(',') != -1)
{
   alert("this is an array!");
}
else
{
   alert("this is not an array!");
}


Or you can use search()

:: Code ::
var myString = "blahblahblah";
if (myString.search(',') != -1)
{
   alert("this is an array!");
}
else
{
   alert("this is not an array!");
}


Note that in either case failure to locate the search term in the string returns a -1, not a 0, or false, since it's returning the string position or the failure code, -1
Back to top
Display posts from previous:   

All times are GMT - 8 Hours