Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the basic knowledge of regular expressions in JavaScript

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces the basic knowledge of regular expressions in JavaScript, which is very detailed and has a certain reference value. Friends who are interested must read it!

In JS, there are two ways to create regular expressions, one is literal and the other is constructor, as follows:

Var regex = /\ wattlespact / or var regex = new RegExp ('\\ wayside')

You may have noticed that using literals is much simpler than constructors.\ w represents a word that matches a single letter, number, or underscore, while when using RegExp constructors, our regularity becomes "\ w" because to represent a backslash\ in a string, we need to escape it, that is, preceded by an escape character\. As you all know, to express a regular matching backslash\ in a literal regular, you only need to write it like this, but to express the regular in a string, it looks like "\". This is because the first two in the string represent a backslash, and the last two also represent a backslash, and finally at the regular level, the result is still\.

For both of the above creation forms, you can add suffix modifiers that can be used individually or in combination:

The copy code is as follows:

/\ global search _ g; / /

/\ walled _ I; / / ignore case

/\ multi-line _

/\ wigzag u; / / unicode

/\ wicked sticky; / /

/\ w+/gi

New RegExp ('\\ wrought, 'gi')

From the English notes, I believe everyone probably knows a thing or two, we need to pay attention to the u and y modifiers, they are new features of ES6, u means to enable Unicode mode, which is especially useful for matching Chinese, while y is sticky, which means "adhesion", which is very similar to g and belongs to global matching, but they also have differences, which we will discuss later.

Canonical correlation method

Now that you have a regular expression object, how do you use it? Both the regular and string in JS provide corresponding methods in the prototype. Let's take a look at the two methods in the regular prototype:

RegExp.prototype.test (str); RegExp.prototype.exec (str)

Both the test () and exec () methods above need to pass in a string to search and match the string. The difference is that the test () method returns true or false, indicating whether the string matches the regular, while the exec () method returns an array of matching results. If it does not match, it only returns a null value. Let's take a look at the difference between them:

/ / RegExp#test () var regex = / hello/;var result = regex.test ('hello world'); / / true// RegExp#exec () var regex = / hello/;var result = regex.exec (' hello world'); / / ['hello']

For the exec () method, if the regular contains a capture group, the match will appear in the result array:

/ / (llo) is a capture group var regex = / he (llo) /; var result = regex.exec ('hello world'); / / [' hello', 'llo']

In development, the test () method is generally used for user input verification, such as mailbox verification, mobile phone number verification, etc., while the exec () method is generally used to obtain valuable information from specific content, such as getting the ID and mailbox type from the user's mailbox input, the attribution of this number from the mobile phone number, and so on.

String correlation method

The above are two methods in the regular prototype, and now let's take a look at which methods are available in the string prototype:

String.prototype.search (regexp); String.prototype.match (regexp); String.prototype.split ([separator [, limit]]); String.prototype.replace (regexp | substr, newSubStr | function)

Let's start with the String#search () method, which matches the string based on regular parameters, returns the index at the first match if the match is successful, and returns-1 if the match fails.

/ / String#search () 'hello world'.search (/ hello/); / / 0'hello world'.search (/ hi/); / /-1

The String#match () method is similar to the RegExp#exec () method and returns an array of results, except that if the regular parameter of String#match () contains the global tag g, only matching substrings will appear in the result and the capture group will be ignored, which is somewhat different from RegExp#exec (). Take a look at the following code:

/ / String#match () 'hello hello'.match (/ he (llo) /); / / [' hello', 'llo'] / / String#match () discards the capture group' hello hello'.match (/ he (llo) / g) when it encounters the global g modifier; / / [hello', 'hello'] / / RegExp#exec () still contains the capture group / he (llo) / g.exec (' hello hello') / / ['hello',' llo']

So, if you need to always return the capture group as a result, you should use the RegExp#exec () method instead of the String#match () method.

Next, let's talk about the String#split () method, which is used to split a string and return an array result containing its substrings, where the separator and limit parameters are optional, separator can be specified as a string or regular, and limit specifies the maximum limit on the number of results returned. If separator is omitted, the method's array result contains only its own source string; if sparator specifies an empty string, the source string is split by characters; if separator is a non-empty string or regular expression, the method splits the source string by this parameter. The following code demonstrates the use of this method:

/ / String#split () 'hello'.split (); / / ["hello"]' hello'.split (''); / / ["h", "e", "l", "l", "o"] 'hello'.split (', 3); / / ["h", "e", "l"] / / specify a non-empty string var source = 'hello world' Var result = source.split (''); / / ["hello", "world"] / / or use the regular expression var result = source.split (/\ s /); / / ["hello", "world"] if separtor is a regular expression and the regular contains a capture group, the capture group will also appear in the result array: / / String#split () regular capture group var source = 'matchandsplit' Var result = source.split ('and'); / / ["match", "split"] var result = source.split (/ and/); / / ["match", "split"] / / regular contains capture group var result = source.split (/ (and) /); / / ["match", "and", "split"]

Finally, let's introduce the String#replace () method, which performs both find and replace operations.

Judging from the function signature above, the method accepts two parameters: the first parameter can be a regular expression or a string, both of which represent the substring to be matched The second parameter can specify a string or a function. If you specify a string, it means that the string will replace the matched substring. If you specify a function, the return value of the function will replace the matched substring.

The String#replace () method will eventually return a new string that has been replaced. The use of the replace method is demonstrated below:

/ / String#replace () var source = 'matchandsplitandreplace';var result = source.replace (' and','-'); / / "match-splitandreplace" / / or var result = source.replace (/ and/, function () {return'-';}); / / "match-splitandreplace"

As you can see from the above code, 'and' is replaced with' -', but we also notice that only the first 'and' is replaced, and the latter is not processed. What we need to understand here is that the String#replace () method only replaces the matching string that occurs for the first time. If we need a global replacement, we need to specify the first parameter as a regular expression and append the global g modifier, like this:

/ / String#replace () globally replace var source = 'matchandsplitandreplace';var result = source.replace (/ and/g,' -'); / / "match-split-replace" var result = source.replace (/ and/g, function () {return'-';}); / / "match-split-replace"

Beginners may wonder when they see the above code. For the second parameter, it is easy to specify a string directly. Why should we use a function and then return a value? Let's look at the following example:

/ / String#replace () replace function argument list var source = 'matchandsplitandreplace';var result = source.replace (/ (a (nd)) / g, function (match, p1, p2, offset, string) {console.group (' match:'); console.log (match, p1, p2, offset, string); console.groupEnd (); return'-';}); / / "match-split-replace"

In the above code, the first parameter is a regular expression, which contains two capture groups (and) and (nd). The second parameter specifies an anonymous function with some parameters in the function list: match, p1, p2, offset, string, corresponding to the matching substring, the first capture group, the second capture group, the index of the matching substring in the source string, and the source string. We can call this anonymous function "replacer" or "replacement function". In the parameter list of replacement function, match, offset and string always exist in each match, while the middle p1, p2 and other capture groups, String#replace () method will fill according to the actual matching situation, of course, we can also get these parameter values according to arguments.

The following is the console print result after the code is run:

Now, specifying a function is much better than specifying a string. We can get this useful information for each match, we can do some manipulation on it, and finally return a value as the new substring to replace. Therefore, it is recommended that you use this method when calling the String#replace () method.

Above are the common methods related to regularities in the String class. It should be noted that the parameters in the String#search () and String#match () method signatures are regular objects. If we pass other types of parameters, they will be implicitly converted to regular objects. The specific step is to call the toString () method of the parameter value to get the string value, and then call new RegExp (val) to get the regular object:

/ /-> String#search (new RegExp (val.toString () '123 123'.search (1); / / 0'true false'.search (true); / / 0x123 123'.search ('\\ s'); / / 3var o = {toString: function () {return'\\ slots;}}; '123 123'.search (o); / / 3max /-> String#match (new RegExp (val.toString ()' 123 123'.match (1) / / ["1"] 'true false'.match (true); / / ["true"]' 123 123'.match ('\\ s'); / / [""] var o = {toString: function () {return'1 (23)';}}; '123 123'.match (o); / / "123", "23"]

The split () and replace () methods do not convert a string to a regular expression object. For other types of values, they will only call their toString () method to convert the parameter value to a string, and will not convert it further to regular. You can test it yourself.

These are all the contents of the article "what are the basics of regular expressions in JavaScript?" Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report