• notice
  • Congratulations on the launch of the Sought Tech site

JavaScript regular expressions

Regular expression syntax structure, create regular expressions, regular expression modifiers, regular expression patterns, use regular expressions


In this section, we are going to learn regular expressions in JavaScript.First, we need to figure out what regular expressions are?

A regular expression is a search pattern formed by a sequence of characters.The search pattern can be used to describe what you want to query. The regular expression can be a simple character or a more complex pattern. Regular expressions can be used for all text search and replace operations.

Regular expression syntax structure

Syntax format:

/pattern/modifiers;

patternIt is the body of the regular expression (used for retrieval) and modifiersis a modifier.The modifier is optional.

Example:

For example, we can try to define a regular expression:

var patt = /xkd/i;

Which /xkd/iis a regular expression, xkdregular expressions body used in a search. iIs a modifier, used to modify the search to be case-insensitive.

Create regular expression

There are two ways to create regular expressions in JavaScript:

The first is the above-mentioned /pattern/modifiersform, for example:

var re = /xkd/;

Create a regular expression in this way.After the script is loaded, the regular expression literal will be compiled.Use this method when the regular expression remains unchanged to get better performance.

Another method is by calling RegExpto create a constructor object, as follows:

var re = new RegExp("xkd");

During the execution of the script, the regular expression created by the constructor will be compiled. If the regular expression will change, or it will be dynamically generated from sources such as user input, you need to use the constructor to create the regular expression.

Example:

An existing string is as follows:

var str = "ABCDEFGHIJKLM";

We need to retrieve the letter "F" in this string.The regular expression is written as follows:

var str = "ABCDEFGHIJKLM";
var result = str.search(/F/); // regular expression
console.log(result); // output: 5

We can see that the output of the code above 5, that is an index of the retrieved string 5, there is a regular expression /F/matching substring.

Regular expression modifiers

  • i : Perform case-insensitive matching.

  • g: Perform a global match (find all matches instead of stopping after the first match is found).

  • m: Perform multi-line matching.

Regular expression pattern

Metacharacters are characters with special meaning:

  • \d: Find numbers, equivalent [0-9].

  • \D: Find non-number, equivalent [0-9].

  • \s: Find blank characters.

  • \S: Find non-blank characters.

  • \b: Match word boundaries.

  • \B: Match non-word boundaries.

  • \w: Equivalent to [a-zA-Z0-9_].

  • \W: Equivalent to [^a-zA-Z0-9_].

  • \n: Matches a newline character.

  • \uxxxx: Find the Unicode character specified by the hexadecimal number xxxx.

Square brackets are used to find characters in a certain range:

  • ^:To...beginning.

  • $: End with...

  • [...]: Any character in square brackets.

  • [^...]: Any character not within the square brackets.

  • [abc]: Find any characters between square brackets.

  • [0-9]: Find any number from 0 to 9.

  • (x|y): Find any options separated by |.

Define quantifiers:

  • *: Match any string containing zero or more n.

  • +: Match any string containing at least one n.

  • ?: Match any string containing zero or one n.

  • {n,m}: Match n to m times, including n and m times.

  • {n,}: Match the previous item at least n times.

  • {n}: Match the previous item n times.

Use regular expressions

Regular expressions can be used for the RegExp execand testmethod and Stringthe matchreplacesearchand splitmethods.

  • exec()Method: It is a regular expression method, used to retrieve the match of the regular expression in the string, and returns an array, if it does not match, it returns null.

Example:

For example, we retrieve the contents of a string, the string of matches have xkdthis substring, it returns an array, otherwise it will return null:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS_Xia Class Island (9xkd.com)</title>
</head>
<body>
<script>
   var name1 = "xkd";
   var name2 = "summer"
   var re = /xkd/;
   var r1 = re.exec(name1);
   var r2 = re.exec(name2);
   console.log(r1);
   console.log(r2);
</script>
</body>
</html>

Open in the browser:

It can be seen from the returned results that for the strings name1 and name2, the substring xkd in name1 is successfully matched, and the match in name2 is unsuccessful, so null is returned.

  • test()Method: A RegExp method to test whether the string matches, and returns true or false.

Example:

For example, if the search string with a letter aat the beginning, it returns true, not false is returned, the code can be written as follows:

// Two strings used for retrieval
var str1 = "123456789";
var str2 = "abcdefg"
// Regular expression, otherwise start with the letter a
var re = /^a/;
// match two strings separately
var r1 = re.test(str1);
var r2 = re.test(str2);
// Output matching results
console.log(r1);
console.log(r2);

Output:

false
true

We can see from the output of the code string str1does not start with a letter (return to false), and the string str2is a beginning (returns true).

  • search()method: Used to retrieve the specified substring in the string, or retrieve the substring that matches the regular expression, and return the starting position of the substring. If it fails, it returns -1.

Example:

For example, we can want to know whether the string variable content contains substrings you:

var content = "Hello xkd, Do you have time tomorrow?";
re = /you/;
var result = content.search(re);
console.log(result)

Output:

14
  • replace()Method: Used to replace some characters with other characters in a string, or replace a substring that matches a regular expression.

Example:

For example, using replacea method of the variable content "xkd" replace "summer":

var content = "Hello xkd, Do you have time tomorrow?";
re = /xkd/;
var result = content.replace(re, 'summer');
console.log(result)

Execute the code, it will output:

Hello summer, Do you have time tomorrow?
  • match()Method: A String method that searches for a match in a string, it returns an array, and returns null if it does not match.

Example:

Using the matchmethod contains a character in the letter x:

var str1 = "hello xkd";
var str2 = "Wow, that's great";
re = /x/;
var result1 = str1.match(re);
var result2 = str2.match(re);
console.log(result1);
console.log(result2);

Execute the code, it will output:

[ 'x', index: 6, input: 'hello xkd', groups: undefined ]
null

The above code, defines two strings, which strings str1are successfully matched to the letter x, returns an array, the array indexas a result of the matching of the start position, inputa search string. And str2there is no letter in x, the match fails, so the output result is null.

Some commonly used regular expressions

In development, we may often use regular expression verification, especially in forms, such as user name, password, phone number, email format, etc., let’s take a look at the following verifications:

  • For example, the user name regular: 3 to 8 digits, which can contain alphanumeric underscores:

var re = /^[a-zA-Z0-9_]{3,8}$/;
  • For example, password regularity: 6 to 16 digits, which can contain alphanumeric characters:

var re = /^[a-zA-Z0-9_]{6,16}$/;
  • For example, phone number regular: can start with 13, 15, 17, 18, a total of 11 digits:

var re = /^1[3578]\d{9}$/;
  • For example, email verification: start with an alphanumeric underscore _, minus sign -, period ., and need to be repeated one or more times [+]. Then a @symbol is inserted in the middle @followed by an alphanumeric underscore _, minus sign -, period ., and it needs to be repeated one or more times [+]. The ending must be a dot, .connecting upper and lower case letters of 2 to 4 digits:

var re = /^([a-zA-Z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;


Tags

Technical otaku

Sought technology together

Related Topic

1 Comments

author

atorvastatin 20mg uk & lt;a href="https://lipiws.top/"& gt;buy generic lipitor& lt;/a& gt; atorvastatin 20mg price

Bymmal

2024-03-11

Leave a Reply

+