Home >Web Front-end >JS Tutorial >Guide to using regular expressions in javascript_javascript tips

Guide to using regular expressions in javascript_javascript tips

WBOY
WBOYOriginal
2016-05-16 16:11:55965browse

How to use

1. Create expression

How to create a regular expression class in JavaScript:

var regex = new RegExp(“d{5}”) or 2.var regex = / d{5}/ (recommended)

/Expression/ is a syntax provided in JavaScript specifically to simplify writing regular expressions. Regular expressions written in // do not need to worry about escape characters.

Methods of RegExp object:

2. Determine whether it matches

test(str) determines whether the string str matches a regular expression, equivalent to IsMatch

Copy code The code is as follows:

var regex = /. @. /;
alert(regex.test("a@b.com"));
alert(regex.test("ab.com"));

3. Get matching results

exec(str) performs search and matching, and the return value is the matching result (*), which is equivalent to match() and matches() in c#

If exec() finds matching text, returns an array of results (the exact matched string plus the results of the extracted group.). Otherwise, returns null. To extract multiple items, you need to repeatedly call exec() similar to the matches() method.

Pay attention to global mode /…../g

In non-global mode, calling exec() once is equivalent to match();

Calling multiple times in global mode is equivalent to matches()

---i ignore case

---mMulti-line matching

The above content is an introduction to the use of regular expressions in JavaScript in this article. I hope you will like it.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn