views:

54

answers:

4

What is the JavaScript equivalent of this .NET code?

var b = Regex.IsMatch(txt, pattern);
+2  A: 
/pattern/.test(txt);

E.g.:

/foo \w+/.test("foo bar");

It returns true for a match, just like IsMatch.

Matthew Flaschen
+1  A: 
var regex = new RegExp(pattern);
var b = regex.test(text);

You can also use var b = /pattern/.test(text) but then you can't use a variable for the regex pattern.

Na7coldwater
1) That's an error, it's `RegExp` NOT `Regex`.
Brock Adams
No, it's a `ReferenceError`. ;)
Matthew Flaschen
couldn't your correct/one-line this to `var b = (new RegExp(pattern)).test(text);`?
Mark E
@Matthew Flaschen: Corrected.
Brock Adams
@Mark I was talking about the `/pattern/` syntax.
Na7coldwater
+3  A: 
var b = /pattern/.test(txt);
Amber
+3  A: 

Here are the useful functions for working with regexes.

  • exec A RegExp method that executes a search for a match in a string. It returns an array of information.
  • test A RegExp method that tests for a match in a string. It returns true or false.
  • match A String method that executes a search for a match in a string. It returns an array of information or null on a mismatch.
  • search A String method that tests for a match in a string. It returns the index of the match, or -1 if the search fails.
  • replace A String method that executes a search for a match in a string, and replaces the matched substring with a replacement substring.
  • split A String method that uses a regular expression or a fixed string to break a string into an array of substrings.

Source: MDC

So to answer your question, as the others have said:

/pattern/.test(txt)

Or, if it is more convenient for your particular use, this is equivalent:

txt.search(/pattern/) !== -1
nickf