开发者

one line match in JS regex

What is the JavaScript equivalent of this .NET code?

var b = Regex开发者_运维问答.IsMatch(txt, pattern);


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


var b = /pattern/.test(txt);


/pattern/.test(txt);

E.g.:

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

It returns true for a match, just like IsMatch.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜