Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use js regular expressions

Shulou Source: shulou.com Published: 2022-05-31 10:38:44 10月13日 Update

This article mainly introduces how to use js regular expressions related knowledge, detailed and easy to understand, simple and fast operation, with a certain reference value, I believe that everyone will have a harvest after reading this article how to use js regular expressions, let's take a look at it.

1. defined

Regular expressions are used to match text according to a "given pattern." Often used to match text such as Email addresses.

There are two ways to create regular expressions:

var regex = /xyz/i;var regex = new RegExp('xyz',i);

The above two ways are equivalent, each creating a new regular expression object. The former is recommended because it is efficient, convenient and intuitive.

2. creation method

There are two ways: constructor and literal

(1) Constructors

var reg=new RegExp(']+%>','g');

(2) literal

var reg=/]%>/g;

g: global, full-text search, default search to the first result and then stop

i: ingore case, ignore case, default case sensitive

m: multiple lines, multiline search (change the meaning of ^and $so that they match the beginning and end of any line, respectively, rather than just the beginning and end of the entire string)

3. usage

exec: RegExp method that performs a search for a match in a string and returns an array (null if no match)

test: RegExp method that tests for a match in a string and returns true or false

match: Executes the String method that finds a match in a string, returning an array and null if there is no match

matchAll: Executes the String method to find all matches in a string, which returns an iterator

search: Tests for a matching String method in a string and returns the index of the location of the match, or-1 on failure

replace: Executes the String method to find a match in a string and replaces the matched substring with a replacement string

split: String method that separates a string using a regular expression or a fixed string and stores the separated substring in an array

For example:

Use the exec method to find a match in a string:

const myRe = /d(b+)d/g;const myArray = myRe.exec("cdbbdbsbz"); About "js regular expression how to use" The content of this article is introduced here, thank you for reading! I believe everyone has a certain understanding of "how to use js regular expressions" knowledge. If you still want to learn more knowledge, please pay attention to the industry information channel.

Tags: Character string method regular expression array knowledge search content function size literal text article test intuitive one line not only value location Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info Redmi macOS MySQL Huawei