23.07.2020

Jquery regex examples. Regular expressions in javascript. Regular Expression Basics Cheat Sheet


The RegExp class in JavaScript is a regular expression - an object that describes a character pattern. RegExp objects are typically created using the special literal syntax below, but they can also be created using the RegExp () constructor.

Syntax

// using special literal syntax var regex = / pattern / flags; // using the constructor var regex = new RegExp ("pattern", "flags"); var regex = new RegExp (/ pattern /, "flags");

Parameter values:

Regular Expression Flags

FlagDescription
gLets you find all matches, rather than stopping after the first match ( global match flag).
iAllows for case-insensitive matching ( ignore case flag).
mThe matching is done across multiple lines. Starting and ending characters (^ and $) are processed on multiple lines, that is, matching occurs at the beginning or end of each line (delimiters \ n or \ r), and not just at the beginning or end of the entire line ( multiline flag).
uThe pattern will be interpreted as a sequence of Unicode code points ( unicode flag).
yMatching occurs by the index pointed to by the lastIndex property of this regular expression, while the match is not performed at a later or earlier index ( sticky flag).

Character sets

Metacharacters

SymbolDescription
. Searches for a single character other than a newline or end-of-line character (\ n, \ r, \ u2028, or \ u2029).
\ dFinds the character of a digit in the basic Latin alphabet. Equivalent to using a character set.
\ DFinds any character that is not a digit in the basic Latin alphabet. Equivalent to the character set [^ 0-9].
\ sFinds a single whitespace character. Whitespace refers to space, tab, page feed, line feed, and other Unicode whitespace characters. Equivalent to the character set [\ f \ n \ r \ t \ v \ u00a0 \ u1680 \ u180e \ u2000 \ u2001 \ u2002 \ u2003 \ u2004 \ u2005 \ u2006 \ u2007 \ u2008 \ u2009 \ u200a \ u2028 \ u2029 \ u202f \ u205f \ u3000].
\ SFinds a single character that is not whitespace. Whitespace refers to space, tab, page feed, line feed, and other Unicode whitespace characters. Equivalent to character set [^ \ f \ n \ r \ t \ v \ u00a0 \ u1680 \ u180e \ u2000 \ u2001 \ u2002 \ u2003 \ u2004 \ u2005 \ u2006 \ u2007 \ u2008 \ u2009 \ u200a \ U2028 \ u2029 \ u202f \ u205f \ u3000].
[\ b]Finds the backspace character (special character \ b, U + 0008).
\0 Finds the character 0 (zero).
\ nFinds the newline character.
\ fFinds the page feed character.
\ rFinds a carriage return character.
\ tFinds a horizontal tab character.
\ vFinds a vertical tab character.
\ wFinds any alphanumeric character in the basic Latin alphabet, including the underscore. Equivalent to a character set.
\ WFinds any character that is not a basic Latin alphabet character. Equivalent to the character set [^ a-Za-z0-9_].
\ cXFinds a control character in a string. Where X is a letter from A to Z. For example, / \ cM / stands for the Ctrl-M character.
\ xhhFinds a character using a hexadecimal value (hh is a two-digit hexadecimal value).
\ uhhhhFinds a character using UTF-16 encoding (hhhh is a four-digit hexadecimal value).
\ u (hhhh) or
\ u (hhhhh)
Finds a character with a Unicode value U + hhhh or U + hhhhh (hexadecimal value). Only when the u flag is given.
\ Indicates that the next character is special and should not be interpreted literally. For characters that are usually treated in a special way, indicates that the next character is not special and should be interpreted literally.

Restrictions

Quantifiers

SymbolDescription
n *Matching occurs on any string containing zero or more occurrences of a character n.
n +Matching occurs with any string containing at least one character n.
n?Matching occurs on any line preceding the element n zero or one time.
n (x)Matches any string containing a sequence of characters n a certain number of times x. X
n (x,) x occurrences of the preceding element n. X must be a positive integer.
n (x, y)Matches any line containing at least x, but no more than with y occurrences of the preceding element n. X and y must be positive integers.
n *?
n +?
n ??
n (x)?
n (x,)?
n (x, y)?
Matching occurs by analogy with the quantifiers *, +,? and (...), however, the search is performed with the smallest possible match. The default is greedy mode,? at the end of the quantifier allows you to specify a "non-greedy" mode in which the matching is repeated as few times as possible.
x (? = y)Allows you to match x, only if for x should y.
x (?! y)Allows you to match x, only if for x it does not follow y.
x | yMatching occurs with any of the specified alternatives.

Grouping and backlinks

SymbolDescription
(x)Finds a symbol x and remember the result of the match ("capturing brackets"). The matched substring can be called from the elements of the resulting array ..., [n], or from the properties of the predefined RegExp $ 1 ..., $ 9 object.
(?: x)Finds a symbol x, but do not remember the result of the match ("non-capturing parentheses"). The matched substring cannot be called from the elements of the resulting array ..., [n], or from the properties of the predefined RegExp $ 1 ..., $ 9 object.
\ nA back reference to the last substring that matches the nth substring in parentheses in the regular expression (parentheses are numbered from left to right). n must be a positive integer.
new RegExp (pattern [, flags])

regex BEFORE

It is known that preferred literal syntax(/ test / i).

If the regular expression is not known in advance, then it is preferable to create the regular expression (in a character string) using the (new RegExp) constructor.

But pay attention, since the "slash" \ plays the role of switching the code, then in the string literal (new RegExp) it has to be written twice: \\

Flags

i ignore case when matching

g global match, as opposed to local (by default, match only the first instance of the pattern) allows matches to all instances of the pattern

Operators

What How Description Usage
i flag makes reg. expression is case insensitive / testik / i
g flag global search / testik / g
m flag can be matched against many strings that can be retrieved from textarea
character class operator character set matching - any character in the range from a to z;
^ operator caret except [^ a-z] - any character EXCEPT characters in the range from a to z;
- hyphen operator indicate the range of values, inclusive - any character in the range from a to z;
\ escaping operator escapes any next character \\
^ match start operator pattern matching must happen at the beginning / ^ testik / g
$ end-of-match operator pattern matching should happen at the end / testik $ / g
? operator? makes the character optional / t? est / g
+ operator + / t + est / g
+ operator + the symbol must be present once or repeatedly / t + est / g
* operator * the symbol must be present once or repeatedly, or not at all / t + est / g
{} operator () set a fixed number of repetitions of the character / t (4) est / g
{,} operator (,) set the number of repetitions of a character within certain limits / t (4.9) est / g

Predefined character classes

Predefined member Comparison
\ t horizontal tab
\ n Line translation
. Any character other than Line feed
\ d Any tenth digit, which is the same as
\ D Any character other than the tenth digit, which is the same as [^ 0-9]
\ w Any character (numbers, letters and underscore) which is the same
\ W Any character other than numbers, letters, and the underscore, which is the same as [^ A-Za-z0-9]
\ s Any space character
\ S Any character other than a space
\ b Word border
\ B NOT a word boundary, but its internal. part

Grouping ()

If an operator, for example, + (/ (abcd) + /), needs to be applied to a member group, you can use parentheses ().

Fixation

The part of the regular expression enclosed in parentheses () is called fixation.

Consider the following example:

/ ^ () k \ 1 /

\ 1 is not any character from a, b, c.
\ 1 is any character that initiates match the first character... That is, the character matched with \ 1 is unknown until the regex is resolved.

Non-fixed groups

Brackets () are used in 2 cases: for grouping and for committing. But there are situations when we need to use () only for grouping, since no commit is required, in addition, by removing unnecessary commits, we make it easier for the regular expression processing engine.

So to prevent commit before the opening parenthesis, you must put:?:

Str = "

Hello world!
"; found = str.match (/<(?:\/?)(?:\w+)(?:[^>] *?)> / i); console.log ("found without fix:", found); // ["
" ]

Test function

Regexp.test ()

The test function checks if the regular expression matches the string (str). Returns either true or false.

Usage example:

Javascript

function codeF (str) (return /^\d(5)-\d(2)/.test(str);) //console.log(codeF("12345-12ss ")); // true //console.log(codeF("1245-12ss ")); // false

Match function

str.match (regexp)

The match function returns an array of values, or null if no match is found. Check it out: if the g flag is absent in the regular expression (for performing a global search), then the match method will return the first match in the string, while, as you can see from the example, in an array of matches get FIXED(the part of the regular expression enclosed in parentheses).

Javascript

str = "For information, see: Chapter 3.4.5.1"; re = / head (\ d + (\. \ d) *) / i // with commits (no global flag) found = str.match (re) console.log (found); // ["Chapter 3.4.5.1", "3.4.5.1", ".1"]

If you provide the match () method with a global regular expression (with flag g), then an array will also be returned, but with GLOBAL matches... That is, no committed results are returned.

Javascript

str = "For information see: Chapter 3.4.5.1, Chapter 7.5"; re = / head (\ d + (\. \ d) *) / ig // no commits - globally found = str.match (re) console.log (found); // ["Chapter 3.4.5.1", "Chapter 7.5"]

Exec function

regexp.exec (str)

The exec function checks if the regular expression matches the string (str). Returns an array of results (with commits) or null. With each subsequent call of the exec method (for example, when using while), the transition to the next global match occurs (due to the automatic update during exec execution of the index of the end of the last search lastIndex) (if the g flag is selected).

Javascript

var html = "
BAM! BUM!
"; var reg = /<(\/?)(\w+)([^>] *?)> / g; //console.log(reg.exec(html)); // ["
"," "," div "," class = "test" "] while ((match = reg.exec (html))! == null) (console.log (reg.exec (html));) / * [" "," "," b "," "] [" "," "," em "," "] ["
"," / "," div "," "] * /

Without a global flag, the match and exec methods work identically. That is, they return an array with the first global match and commits.

Javascript

// match var html = "
BAM! BUM!
"; var reg = /<(\/?)(\w+)([^>] *?)> /; // no global console.log (html.match (reg)); // ["
"," "," div "," class = "test" "] // exec var html ="
BAM! BUM!
"; var reg = /<(\/?)(\w+)([^>] *?)> /; // no global console.log (reg.exec (html)); // ["
"," "," div "," class = "test" "]

Replace function

str.replace (regexp, newSubStr | function)
  • regexp - reg. expression;
  • newSubStr - the line to which the found expression in the text is changed;
  • function - called for each match found with a variable parameter list (recall that a global search in a string finds all instances of a pattern match).

The return value of this function serves as a replacement.

Function parameters:

  • 1 - Complete matched substring.
  • 2 - The meaning of bracket groups (fixations).
  • 3 - Index (position) of the match in the original string.
  • 4 - The original string.

The method does not change the calling string, but returns a new one after replacing the matches. To perform a global search and replace, use regexp with the g flag.

"GHGHGHGTTTT" .replace (// g, "K"); // "KKKKKKKKKKK"

Javascript

function upLetter (allStr, letter) (return letter.toUpperCase ();) var res = "border-top-width" .replace (/ - (\ w) / g, upLetter); console.log (res); // borderTopWidth

Regular Expressions allow flexible search for words and expressions in texts with the aim of deleting, extracting or replacing them.

Syntax:

// The first way to create a regular expression var regexp = new RegExp ( sample,modifiers); // Second way to create a regular expression var regexp = / sample/modifiers;

sample allows you to set the character pattern for the search.

modifiers allow you to customize the search behavior:

  • i- case-insensitive search;
  • g- global search (all matches in the document will be found, not just the first one);
  • m- multi-line search.

Search for words and expressions

The most simple application regex is the search for words and expressions in various texts.

Here's an example of using search with modifiers:

// Set the regular expression rv1 rv1 = / Russia /; // Set the regular expression rv2 rv2 = / Russia / g; // Set the regular expression rv3 rv3 = / Russia / ig; // Bold type indicates where matches will be found in the text when using // the expression rv1: Russia is the largest state in the world. Russia shares borders with 18 countries. RUSSIA is the successor state of the USSR. // Bold type indicates where matches will be found in the text when using // the expression rv2: Russia is the largest state in the world. Russia shares borders with 18 countries. RUSSIA is the successor state of the USSR. "; // Bold type indicates where matches will be found in the text when using // the expression rv3: Russia is the largest state in the world. Russia shares borders with 18 countries. RUSSIA is the successor state of the USSR.";

Special symbols

In addition to regular characters, regular expression patterns can use Special symbols(metacharacters). Special characters with descriptions are shown in the table below:

Special character Description
. Matches any character other than the end-of-line character.
\ w Matches any alphabetic character.
\ W Matches any non-alphabetic character.
\ d Matches characters that are numbers.
\ D Matches characters that are not numbers.
\ s Matches whitespace characters.
\ S Matches non-whitespace characters.
\ b Matches will only be searched at word boundaries (at the beginning or at the end).
\ B Matches will only be searched on non-word boundaries.
\ n Matches a line feed character.

/ * Expression reg1 will find all words starting with two arbitrary letters and ending with "vet". Since the words in the sentence are separated by a space, then at the beginning and at the end we add the special character \ s) * / reg1 = / \ s..vet \ s / g; txt = "hello covenant corduroy closet"; document.write (txt.match (reg1) + "
"); / * The reg2 expression will find all words starting with three arbitrary letters and ending with" vet "* / reg2 = / \ s ... vet \ s / g; document.write (txt.match (reg2) +"
"); txt1 =" hello hello hello "; / * The reg3 expression will find all words that start with" at "followed by 1 digit and end with" vet "* / var reg3 = / for \ dvet / g; document .write (txt1.match (reg3) + "
"); // Expression reg4 will find all digits in the text var reg4 = / \ d / g; txt2 =" 5 years of study, 3 years of sailing, 9 years of shooting. "Document.write (txt2.match (reg4) +"
");

Quick view

Symbols in square brackets

Using square brackets [keiu] You can specify a group of characters to search for.

The ^ character in front of a group of characters in square brackets [^ kwg] indicates that you need to search for all characters of the alphabet except the specified ones.

Using a dash (-) between characters in square brackets [a-z] You can specify the range of characters to search for.

You can also search for numbers with square brackets.

// Set the regular expression reg1 reg1 = / \ sko [tdm] \ s / g; // Set a line of text txt1 txt1 = "cat braid code chest of drawers com carpet"; // Search for the string txt1 using the regular expression reg1 document.write (txt1.match (reg1) + "
"); reg2 = / \ slo [^ tg] / g; txt2 =" slot elephant syllable "; document.write (txt2.match (reg2) +"
"); reg3 = // g; txt3 =" 5 years of study, 3 years of sailing, 9 years of shooting "; document.write (txt3.match (reg3));

Quick view

Quantifiers

Quantifier is a construction that allows you to specify how many times the preceding character or group of characters should be matched.

Syntax:

// The preceding character must occur x - times (x)// The preceding character must occur from x to y times inclusive (x, y)// The preceding character must appear at least x times (x,)// Indicates that the preceding character must occur 0 or more times * // Indicates that the preceding character must occur 1 or more times + // Indicates that the preceding character should occur 0 or 1 times ?


// Set the regular expression rv1 rv1 = / ko (5) scale / g // Set the regular expression rv2 rv2 = / ko (3,) scale / g // Set the regular expression rv3 rv3 = / ko + scale / g // Set regular expression rv4 rv4 = / ko? shka / g // Set a regular expression rv5 rv5 = / co * shka / g // Bold type shows where matches will be found in the text // expression rv1: kshka cat kitty kooshka koooooshka koooooshka koooooooshka // Bold type shows where matches will be found in the text when using // expressions rv2: kshka cat kooshka kooooooooooooooooooooooooooooooooooooooooooooooooooo// Bold indicates where matches will be found in the text when using // the expression rv3: kshka cat// Bold indicates where matches will be found in the text // using the rv4 expression: kshka koshka koooshka koooooshka kooooooshka koooooooooooo // Bold indicates where matches will be found in the text // using the rv5 expression: cat

Note: if you want to use any special character (such as. * +? or ()) as usual, you must precede it with \.

Using parentheses

By enclosing a portion of a regular expression pattern in parentheses, you tell the expression to remember the match found by that portion of the pattern. The saved match can be used later in your code.

For example, the regular expression / (Dmitry) \ sVasiliev / will find the string "Dmitry Vasiliev" and remember the substring "Dmitry".

In the example below, we use the replace () method to change the order of words in the text. We use $ 1 and $ 2 to refer to the stored matches.

Var regexp = / (Dmitry) \ s (Vasiliev) /; var text = "Dmitry Vasiliev"; var newtext = text.replace (regexp, "$ 2 $ 1"); document.write (newtext);

Quick view

Parentheses can be used to group characters before quantifiers.

Some people, when faced with a problem, think, "Oh, I'm using regular expressions." They now have two problems.
Jamie Zawinski

Yuan-Ma said, “It takes a lot of force to cut wood across the wood structure. It takes a lot of code to program across the structure of the problem.
Master Yuan-Ma, "The Book of Programming"

Programming tools and techniques survive and spread in a chaotic evolutionary way. Sometimes it is not the beautiful and brilliant who survive, but simply those who work well enough in their field - for example, if they are integrated into another successful technology.

In this chapter, we will discuss such a tool, regular expressions. This is a way to describe patterns in string data. They create a small, separate language that comes with JavaScript and many other languages ​​and tools.

Regulars are both weird and extremely useful. Their syntax is cryptic, and the programming interface in JavaScript is awkward to them. But it is a powerful tool for exploring and processing strings. By dealing with them, you will become a more efficient programmer.

Creating a regular expression

Regular is an object type. It can be created by calling the RegExp constructor, or by writing the desired template surrounded by slashes.

Var re1 = new RegExp ("abc"); var re2 = / abc /;

Both of these regular expressions represent the same pattern: the “a” character, followed by the “b” character, followed by the “c” character.

If you use the RegExp constructor, then the pattern is written as a regular string, so all the rules regarding backslashes apply.

The second entry, where the pattern is between slashes, handles backslashes differently. First, since the template ends with a forward slash, we need to put a backslash in front of the forward slash that we want to include in our template. Also, backslashes not part of special characters such as \ n will be preserved (rather than ignored as in strings), and will change the meaning of the pattern. Some characters, such as the question mark or plus, have a special meaning in regular patterns, and if you need to find such a character, you must also precede it with a backslash.

Var eighteenPlus = / eighteen \ + /;

To know which characters to precede with a slash, you need to learn a list of all the special characters in the regulars. This is unrealistic at this time, so when in doubt, just put a backslash in front of any character that is not a letter, number, or space.

Checking for matches

Regulars have several methods. The simplest is test. If you pass it a string, it will return a boolean indicating whether the string contains an occurrence of the given pattern.

Console.log (/abc/.test ("abcde")); // → true console.log (/abc/.test ("abxde")); // → false

Regularity, consisting only of non-special characters, is simply a sequence of those characters. If abc is somewhere in the string we are testing (not just at the beginning), test will return true.

Looking for a character set

To find out if a string contains abc could have been done using indexOf. Regulars allow you to go further and create more complex patterns.

Let's say we need to find any number. When we put a set of characters in square brackets in a regex, it means that this part of the expression matches any of the characters in the brackets.

Both expressions are in lines containing a digit.

Console.log (//. Test ("in 1992")); // → true console.log (//. Test ("in 1992")); // → true

In square brackets, a dash between two characters is used to specify a range of characters, where the sequence is specified by the Unicode encoding. Characters from 0 to 9 are there just in a row (codes from 48 to 57), so it captures them all and matches any digit.

Several character groups have their own built-in abbreviations.

\ d Any digit
\ w Alphanumeric character
\ s Whitespace character (space, tab, line feed, etc.)
\ D is not a digit
\ W is not an alphanumeric character
\ S is not a whitespace character
... any character except line feed

Thus, you can set a date and time format like 01/30/2003 15:20 with the following expression:

Var dateTime = / \ d \ d- \ d \ d- \ d \ d \ d \ d \ d \ d: \ d \ d /; console.log (dateTime.test ("01/30/2003 15:20")); // → true console.log (dateTime.test ("30-jan-2003 15:20")); // → false

Looks awful, doesn't it? Too many backslashes that make the pattern difficult to understand. We'll improve it slightly later.

Backslashes can also be used in square brackets. For example, [\ d.] Means any digit or period. Note that the dot inside the square brackets loses its special meaning and becomes just a dot. The same goes for other special characters like +.

You can invert the character set — that is, say that you want to find any character other than the one in the set — by placing a ^ immediately after the opening square bracket.

Var notBinary = / [^ 01] /; console.log (notBinary.test ("1100100010100110")); // → false console.log (notBinary.test ("1100100010200110")); // → true

Repeating parts of the pattern

We know how to find one number. And if we need to find the whole number - a sequence of one or more digits?

If you put a + after something in a regular grid, it means that this element can be repeated more than once. / \ d + / means one or more digits.

Console.log (/ "\ d +" /. Test ("" 123 "")); // → true console.log (/ "\ d +" /. Test ("" "")); // → false console.log (/ "\ d *" /. Test ("" 123 "")); // → true console.log (/ "\ d *" /. Test ("" "")); // → true

The asterisk * has almost the same meaning, but it allows the pattern to be present zero times. If there is an asterisk after something, then it never prevents the pattern from being found in the string - it just appears there zero times.

The question mark makes part of the pattern optional, that is, it can occur zero or one times. In the following example, the u character may appear, but the pattern matches when it does not exist.

Var neighbor = / neighbou? R /; console.log (neighbor.test ("neighbor")); // → true console.log (neighbor.test ("neighbor")); // → true

Curly braces are used to specify the exact number of times that the pattern must occur. (4) after the element means that it must appear 4 times in the line. You can also set a gap: (2,4) means that the element must occur at least 2 and no more than 4 times.

Another version of the date and time format, where days, months and hours of one or two digits are allowed. It's also a little more readable.

Var dateTime = / \ d (1,2) - \ d (1,2) - \ d (4) \ d (1,2): \ d (2) /; console.log (dateTime.test ("30-1-2003 8:45")); // → true

You can use open ended gaps by omitting one of the numbers. (, 5) means that the pattern can occur from zero to five times, and (5,) - from five or more.

Grouping subexpressions

You can use parentheses to use the * or + operators on multiple elements at once. The parenthesized part of the regex counts as one element from the point of view of the operators.

Var cartoonCrying = / boo + (hoo +) + / i; console.log (cartoonCrying.test ("Boohoooohoohooo")); // → true

The first and second pluses only apply to the second o in boo and hoo. The third + refers to the whole group (hoo +), finding one or more such sequences.

The letter i at the end of the expression makes the regex case insensitive — so that B is the same as b.

Matches and groups

The test method is the simplest method for checking regulars. It only reports whether a match was found or not. Regulars also have an exec method that will return null if nothing was found, and otherwise return an object with information about the match.

Var match = /\d+/.exec("one two 100 "); console.log (match); // → ["100"] console.log (match.index); // → 8

The returned exec object has an index property, which contains the number of the character from which the match occurred. In general, the object looks like an array of strings, where the first element is a string that was checked for a match. In our example, this will be the sequence of numbers we were looking for.

Strings have a match method that works in much the same way.

Console.log ("one two 100" .match (/ \ d + /)); // → ["100"]

When a regular expression contains parentheses grouped subexpressions, the text that matches those groups will also appear in the array. The first element is always a complete match. The second is the part that coincided with the first group (the one with the parentheses met before anyone else), then with the second group, and so on.

Var quotedText = / "([^"] *) "/; console.log (quotedText.exec (" she said "hello" ")); // → [" "hello" "," hello "]

When a group is not found at all (for example, if there is a question mark behind it), its position in the array contains undefined. If the group has been matched several times, then the array will contain only the last match.

Console.log (/ bad (ly)? /. Exec ("bad")); // → ["bad", undefined] console.log (/ (\ d) + /. Exec ("123")); // → ["123", "3"]

Groups are useful for extracting portions of strings. If we don't just need to check if there is a date in the string, but extract it and create an object representing the date, we can enclose the sequences of numbers in parentheses and select the date from the exec result.

But first, a little digression in which we will learn the preferred way of storing date and time in JavaScript.

Date type

JavaScript has a standard object type for dates — more precisely, points in time. It's called Date. If you just create a date object with new, you get the current date and time.

Console.log (new Date ()); // → Sun Nov 09 2014 00:07:57 GMT + 0300 (CET)

You can also create an object containing a given time

Console.log (new Date (2015, 9, 21)); // → Wed Oct 21 2015 00:00:00 GMT + 0300 (CET) console.log (new Date (2009, 11, 9, 12, 59, 59, 999)); // → Wed Dec 09 2009 12:59:59 GMT + 0300 (CET)

JavaScript uses a convention where month numbers start at zero and day numbers start at one. This is stupid and ridiculous. Watch out.

The last four arguments (hours, minutes, seconds, and milliseconds) are optional and, if missing, are set to zero.

Timestamps are stored as the number of milliseconds since the beginning of 1970. For times before 1970, negative numbers are used (this is due to the Unix time convention, which was created around that time). The getTime method of the date object returns this number. It is naturally large.
console.log (new Date (2013, 11, 19) .getTime ()); // → 1387407600000 console.log (new Date (1387407600000)); // → Thu Dec 19 2013 00:00:00 GMT + 0100 (CET)

Given a single argument to the Date constructor, it is treated as the number of milliseconds. You can get the current milliseconds by creating a Date object and calling the getTime method, or by calling the Date.now function.

The Date object has methods getFullYear, getMonth, getDate, getHours, getMinutes, and getSeconds to retrieve its components. There is also a getYear method that returns a rather useless two-digit code like 93 or 14.

By enclosing the required parts of the pattern in parentheses, we can create a date object directly from a string.

Function findDate (string) (var dateTime = / (\ d (1,2)) - (\ d (1,2)) - (\ d (4)) /; var match = dateTime.exec (string); return new Date (Number (match), Number (match) - 1, Number (match));) console.log (findDate ("30-1-2003")); // → Thu Jan 30 2003 00:00:00 GMT + 0100 (CET)

Word and line boundaries

Unfortunately, findDate will just as happily extract the meaningless date 00-1-3000 from the string "100-1-30000". The match can happen anywhere in the string, so in this case it just starts at the second character and ends at the penultimate one.

If we need to force a match to take the entire string, we use the ^ and $ labels. ^ matches the beginning of the line and $ matches the end. Therefore, / ^ \ d + $ / matches a string containing only one or more digits, / ^! / Matches a string that starts with an exclamation mark, and / x ^ / does not match any string (there cannot be x).

If, on the other hand, we just need to make sure that the date starts and ends at a word boundary, we use the \ b label. A word boundary can be the beginning or end of a line, or any part of a line where there is an alphanumeric \ w character on one side and a non-alphanumeric character on the other.

Console.log (/cat/.test ("concatenate")); // → true console.log (/ \ bcat \ b / .test ("concatenate")); // → false

Note that the border mark is not a symbol. This is simply a constraint, meaning that a match occurs only if a certain condition is met.

Choice templates

Let's say you need to find out if the text contains not just a number, but a number followed by pig, cow, or chicken in the singular or plural.

One could write three regulars and check them one by one, but there is a better way. Symbol | indicates a choice between templates to the left and to the right of it. And we can say the following:

Var animalCount = / \ b \ d + (pig | cow | chicken) s? \ B /; console.log (animalCount.test ("15 pigs")); // → true console.log (animalCount.test ("15 pigchickens")); // → false

The parentheses delimit the portion of the pattern to which | applies, and you can place many of these operators one after the other to indicate more than two choices.

Search engine

Regular expressions can be thought of as flowcharts. The following diagram describes the last livestock example.

An expression matches a string if a path can be found from the left to the right of the diagram. We remember the current position in the line, and each time we go through the rectangle, we check that the part of the line immediately after our position in it coincides with the contents of the rectangle.

This means that checking the coincidence of our regular pattern in the line "the 3 pigs" when passing through the flowchart looks like this:

At position 4 there is a word boundary, and we pass the first rectangle
- starting from the 4th position, we find the number, and we go through the second rectangle
- at position 5, one path closes back before the second rectangle, and the second goes further to the rectangle with a space. We have a space, not a number, and we choose the second path.
- now we are at position 6, the beginning of the “pigs”, and at the triple fork of the paths. There is no “cow” or “chicken” in the line, but there is “pig”, so we choose this path.
- at position 9 after the triple forking, one path bypasses “s” and goes to the last rectangle with a word boundary, and the other goes through “s”. We have s, so we go there.
- at position 10 we are at the end of the line, and only the word boundary can match. The end of the line is considered a border and we go through the last rectangle. And so we have successfully found our template.

Basically, regular expressions work like this: the algorithm starts at the beginning of a line and tries to find a match there. In our case, there is a word border, so it goes through the first rectangle - but there is no number, so it stumbles on the second rectangle. Then it moves to the second character in the line, and tries to find a match there ... And so on, until it finds a match or reaches the end of the line, in which case no match was found.

Kickbacks

The regular / \ b (+ b | \ d + | [\ da-f] h) \ b / matches either a binary number followed by b, or a decimal number without a suffix, or hexadecimal (digits 0 through 9 or symbols a through h) followed by h. Corresponding diagram:

When looking for a match, it can happen that the algorithm went down the upper path (binary number), even if there is no such number in the string. If there is a string “103” there, for example, it is clear that only after reaching the number 3, the algorithm will understand that it is on the wrong path. In general, the line matches the regular, just not in this thread.

Then the algorithm rolls back. At the fork, he remembers the current position (in our case, this is the beginning of the line, right after the word boundary) so that you can go back and try another path if the chosen one does not work. For the string “103”, after meeting with the triplet, it will return and try to go through the path for decimal numbers. This will work, so a match will be found.

The algorithm stops as soon as it finds a complete match. This means that even if several variations may work, only one of them is used (in the order in which they appear in the regular season).

Rollbacks happen when you use repetition operators such as + and *. If you are looking for /^.*x/ in the string "abcxe", part of the regular. * Will try to swallow the whole string. The algorithm will then figure out that it also needs “x”. Since there is no “x” after the end of the line, the algorithm will try to find a match by going back one character. There is no x after abcx either, then it rolls back again, already to the substring abc. And after the line, it finds x and reports a successful match, at positions 0 to 4.

It is possible to write a regex that will lead to multiple rollbacks. This problem occurs when a pattern can match the input in many different ways. For example, if we misspelled the regex for binary numbers, we might accidentally write something like / (+) + b /.

If the algorithm searches for such a pattern in a long string of zeros and ones that does not contain a “b” at the end, it will first go through the inner loop until it runs out of digits. Then he will notice that there is no “b” at the end, will roll back one position, walk along the outer loop, surrender again, try to roll back one more position along the inner loop ... And he will continue to search in this way, using both loops. That is, the amount of work with each character of the string will be doubled. Even for several dozen characters, finding a match will take a very long time.

Replace method

Strings have a replace method that can replace part of a string with another string.

Console.log ("dad" .replace ("p", "m")); // → map

The first argument can also be regular, in which case the first occurrence of the regular in the string is replaced. When the “g” (global) option is added to the regular, all occurrences are replaced, not just the first

Console.log ("Borobudur" .replace (//, "a")); // → Barobudur console.log ("Borobudur" .replace (// g, "a")); // → Barabadar

It would make sense to pass the "replace all" option through a separate argument, or through a separate method of type replaceAll. Unfortunately, the option is passed through the regular season itself.

The full power of regulars is revealed when we use the links to the groups found in the string, given in the regular. For example, we have a string containing the names of people, one name per line, in the format "Last Name, First Name". If we need to swap them and remove the comma to get "First Name Last Name", we write the following:

Console.log ("Hopper, Grace \ nMcCarthy, John \ nRitchie, Dennis" .replace (/ ([\ w] +), ([\ w] +) / g, "$ 2 $ 1")); // → Grace Hopper // John McCarthy // Dennis Ritchie

The $ 1 and $ 2 in the replacement string refer to the parenthesized character groups. $ 1 is replaced with the text that matched the first group, $ 2 with the second group, and so on, up to $ 9. The entire match is contained in the $ & variable.

You can also pass a function as the second argument. For each replacement, a function will be called, the arguments of which will be the found groups (and the entire matching part of the string as a whole), and its result will be inserted into a new string.

Simple example:

Var s = "the cia and fbi"; console.log (s.replace (/ \ b (fbi | cia) \ b / g, function (str) (return str.toUpperCase ();))); // → the CIA and FBI

And here's a more interesting one:

Var stock = "1 lemon, 2 cabbages, and 101 eggs"; function minusOne (match, amount, unit) (amount = Number (amount) - 1; if (amount == 1) // there is only one left, remove the "s" at the end unit = unit.slice (0, unit.length - 1); else if (amount == 0) amount = "no"; return amount + "" + unit;) console.log (stock.replace (/ (\ d +) (\ w +) / g, minusOne)); // → no lemon, 1 cabbage, and 100 eggs

The code takes a string, finds all occurrences of numbers followed by a word, and returns a string with each number decremented by one.

The group (\ d +) goes into the amount argument, and (\ w +) goes into unit. The function converts amount to a number - and it always works, because our pattern is just \ d +. And then he makes changes to the word, in case there is only 1 item left.

Greed

It's easy to write a function using replace that removes all comments from JavaScript code. Here's a first try:

Function stripComments (code) (return code.replace (/\/\/.* | \ / \ * [^] * \ * \ // g, "");) console.log (stripComments ("1 + / * 2 * / 3 ")); // → 1 + 3 console.log (stripComments ("x = 10; // ten!")); // → x = 10; console.log (stripComments ("1 / * a * / + / * b * / 1")); // → 1 1

The part before the "or" operator matches two slashes, followed by any number of characters, except for line feed characters. The part that removes multi-line comments is more complicated. We use [^], i.e. any character that is not empty as a way to find any character. We cannot use period because block comments continue on a new line, and the line feed character does not match the period.

But the output from the previous example is wrong. Why?

The [^] * part will first try to capture as many characters as it can. If, because of this, the next part of the regex does not find a match, it will roll back one character and try again. In the example, the algorithm tries to grab the entire line and then rolls back. When he rolls back 4 characters, he will find in the line * / - and this is not what we wanted. We wanted to capture only one comment, and not go to the end of the line and find the last comment.

Because of this, we say that the repetition operators (+, *,?, And ()) are greedy, that is, they first grab as much as they can and then go backwards. If you put a question after such an operator (+ ?, * ?, ??, ()?), They become non-greedy, and start finding the smallest possible occurrences.

And this is what we need. By making the asterisk match the minimum possible number of characters on the line, we consume only one block of comments, and nothing more.

Function stripComments (code) (return code.replace (/\/\/.* | \ / \ * [^] *? \ * \ // g, "");) console.log (stripComments ("1 / * a * / + / * b * / 1 ")); // → 1 + 1

Many errors arise when using greedy operators instead of non-greedy ones. When using a repeat operator, always consider the non-greedy operator first.

Dynamically creating RegExp objects

In some cases, the exact pattern is not known at the time of writing the code. For example, you will need to search for the user's name in the text, and enclose it in underscores. Since you only know the name after starting the program, you cannot use the slash notation.

But you can build a string and use the RegExp constructor. Here's an example:

Var name = "harry"; var text = "And Harry has a scar on his forehead."; var regexp = new RegExp ("\\ b (" + name + ") \\ b", "gi"); console.log (text.replace (regexp, "_ $ 1_")); // → And _Harry_ has a scar on his forehead.

When creating word boundaries, we have to use double slashes, because we write them on a normal line, not in a regular line with forward slashes. The second argument for RegExp contains options for regulars - in our case “gi”, ie. global and case-insensitive.

But what if the name is "dea + hlrd" (if our user is a kulhacker)? As a result, we will get a meaningless regex that will not find matches in the string.

We can add backslashes before any character we don't like. We cannot add backslashes before letters, because \ b or \ n are special characters. But adding slashes before any non-alphanumeric characters is easy.

Var name = "dea + hlrd"; var text = "This dea + hlrd got everyone out."; var escaped = name.replace (/ [^ \ w \ s] / g, "\\ $ &"); var regexp = new RegExp ("\\ b (" + escaped + ") \\ b", "gi"); console.log (text.replace (regexp, "_ $ 1_")); // → This _dea + hlrd_ got everyone.

Search method

The indexOf method cannot be used with regular patterns. But there is a search method that just expects a regular. Like indexOf, it returns the index of the first occurrence, or -1 if it didn't.

Console.log ("word" .search (/ \ S /)); // → 2 console.log ("" .search (/ \ S /)); // → -1

Unfortunately, there is no way you can tell the method to look for a match starting at a specific offset (as can be done with indexOf). It would be helpful.

LastIndex property

The exec method also does not provide a convenient way to start a search from a given position in a string. But an inconvenient way gives.

The regular object has properties. One of them is source, which contains a string. One more thing is lastIndex, which controls, in some conditions, where the next search for occurrences will start.

These conditions include the need for the global option g, and that the search should be done using the exec method. A smarter solution would be to just allow an extra argument to be passed to exec, but sanity is not a fundamental feature in the JavaScript regulars interface.

Var pattern = / y / g; pattern.lastIndex = 3; var match = pattern.exec ("xyzzy"); console.log (match.index); // → 4 console.log (pattern.lastIndex); // → 5

If the search was successful, the exec call updates the lastIndex property to point to the position after the match found. If there is no success, lastIndex is set to zero - just like the lastIndex of the newly created object.

When using a global regular variable and multiple exec calls, these automatic updates lastIndex can lead to problems. Your regular season may start searching from the position left over from the previous call.

Var digit = / \ d / g; console.log (digit.exec ("here it is: 1")); // → ["1"] console.log (digit.exec ("and now: 1")); // → null

Another interesting effect of the g option is that it changes how the match method works. When called with this option, instead of returning an array like exec, it finds all occurrences of the pattern in the string and returns an array of the substrings found.

Console.log ("Banana" .match (/ en / g)); // → ["an", "an"]

So be careful with global regex variables. Where they are needed — calls to replace, or places where you specifically use lastIndex — are probably all the cases in which they should be used.

Loops over occurrences

A typical task is to iterate over all occurrences of the pattern in a string so that you can access the match object in the body of the loop using lastIndex and exec.

Var input = "A line with 3 numbers in it ... 42 and 88."; var number = / \ b (\ d +) \ b / g; var match; while (match = number.exec (input)) console.log ("Found", match, "on", match.index); // → Found 3 in 14 // Found 42 in 33 // Found 88 in 40

It takes advantage of the fact that the assignment value is the assigned value. Using match = re.exec (input) as a condition in the while loop, we search at the beginning of each iteration, store the result in a variable, and end the loop when all matches are found.

Parsing INI files

To conclude the chapter, consider a problem using regulars. Imagine that we are writing a program that collects information about our enemies over the Internet in automatic mode... (We will not write the entire program, only the part that reads the file with settings. Sorry.) The file looks like this:

Searchengine = http: //www.google.com/search? Q = $ 1 spitefulness = 9.7; comments are preceded by a semicolon; each section refers to a different enemy fullname = Larry Doe type = kindergarten bull website = http: //www.geocities.com/CapeCanaveral/11451 fullname = Gargamel type = evil wizard outputdir = / home / marijn / enemies / gargamel

The exact file format (which is quite widely used, and is usually called INI) is as follows:

Blank lines and lines starting with semicolons are ignored
- lines enclosed in square brackets start a new section
- strings containing an alphanumeric identifier followed by = add a setting in this section

Everything else is incorrect data.

Our task is to convert such a string into an array of objects, each with a name property and an array of settings. Each section needs one object, and another one for the global settings at the top of the file.

Since the file needs to be parsed line by line, it is a good idea to start by breaking the file into lines. To do this, in Chapter 6 we used string.split ("\ n"). Some operating systems use not one \ n character for line feed, but two - \ r \ n. Since the split method accepts regular expressions as an argument, we can split lines with the expression / \ r? \ N /, which allows both single \ n and \ r \ n between lines.

Function parseINI (string) (// Let's start with the object containing the top-level settings var currentSection = (name: null, fields:); var categories =; string.split (/ \ r? \ N /). ForEach (function (line ) (var match; if (/^\s*(;.*)?$/.test(line)) (return;) else if (match = line.match (/^\ [(.*)\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\led\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ots $ help you match) /)) (currentSection = (name: match, fields:); categories.push (currentSection);) else if (match = line.match (/ ^ (\ w +) = (. *) $ /)) (currentSection. fields.push ((name: match, value: match));) else (throw new Error ("The line" "+ line +" "contains invalid data.");))); return categories;)

The code goes through all the lines, updating the current section object. First, it checks to see if the line can be ignored using the regular pattern /^\s*(;.*)?$/. Do you know how it works? The part between the brackets matches the comments, eh? makes it so that the regex will also match lines consisting of only spaces.

If the line is not a comment, the code checks to see if it starts a new section. If so, it creates a new object for the current section, to which subsequent settings are added.

The last thing that makes sense is that the string is a normal setting, in which case it is added to the current object.

If none of the options worked, the function generates an error.

Notice how frequent use of ^ and $ makes sure that the expression matches the entire string, not a part. If they are not used, the code will generally work, but sometimes it will produce strange results and it will be difficult to track down the error.

The if (match = string.match (...)) construct is like a trick that uses assignment as a condition in a while loop. Often times, you don't know that a call to match will succeed, so you can only access the resulting object inside the if block that checks for it. In order not to break the beautiful chain of if checks, we assign the search result to a variable, and immediately use this assignment as a check.

International Symbols

Due to the initially simple implementation of the language, and the subsequent fixation of such an implementation "in granite", JavaScript regulars get stupid with characters that are not found in English language... For example, the character "letters" from the point of view of JavaScript regulars, can be one of the 26 letters of the English alphabet, and for some reason still an underscore. Letters like é or β, which are unambiguous letters, do not match \ w (and will match \ W, which is a non-letter).

By a strange coincidence, historically \ s (space) matches all characters that Unicode considers whitespace, including things like the non-breaking space or the Mongolian vowel separator.

Some implementations of regulars in other languages ​​have a special syntax for finding special categories of Unicode characters, such as all uppercase, all punctuation, or control characters. There are plans to add such categories to JavaScript as well, but they probably won't be implemented soon.

Outcome

Regulars are objects representing search patterns in strings. They use their own syntax to express these patterns.

/ abc / A sequence of characters
// Any character from the list
/ [^ abc] / Any character except characters from the list
// Any character in the range
/ x + / One or more occurrences of pattern x
/ x +? / One or more occurrences, non-greedy
/ x * / Zero or more occurrences
/ x? / Zero or one occurrences
/ x (2,4) / Two to four occurrences
/ (abc) / Group
/ a | b | c / Any of several patterns
/ \ d / Any digit
/ \ w / Any alphanumeric character ("letter")
/ \ s / Any whitespace character
/./ Any character except line breaks
/ \ b / Word boundary
/ ^ / Beginning of line
/ $ / End of line

The regex has a test method to check if there is a pattern in the string. There is an exec method that returns an array containing all found groups. The array has an index property, which contains the number of the character from which the match occurred.

Strings have a match method for finding patterns, and a search method that only returns the starting position of the match. The replace method can replace occurrences of a pattern with another string. In addition, you can pass a function to replace that will build a replacement string based on the template and found groups.

Regulars have settings that are written after the closing slash. The i option makes the regex case insensitive, and the g option makes it global, which, among other things, makes the replace method replace all occurrences it finds, not just the first one.

The RegExp constructor can be used to create regulars from strings.

Regulars are a sharp tool with an awkward handle. They greatly simplify some tasks, and can become unmanageable when solving other, complex tasks. Part of being able to use regular blocks is being able to resist the temptation to cram a task into them for which they were not intended.

Exercises

Inevitably, when solving problems, you will have incomprehensible cases, and you can sometimes despair seeing the unpredictable behavior of some regulars. Sometimes it helps to study the behavior of the regular season through an online service such as debuggex.com, where you can see its visualization and compare it with the desired effect.
Regular golf
"Golf" in the code is called a game where you need to express a given program with the minimum number of characters. Regular golf is a practical exercise in writing the smallest possible regulars to find a given pattern, and nothing else.

For each of the substitutions, write a regex to check if they are in the string. The regex should only find these specified substrings. Don't worry about word boundaries unless specifically mentioned. When you have a working regular, try decreasing it.

Car and cat
- pop and prop
- ferret, ferry, and ferrari
- Any word ending in ious
- A space followed by a period, comma, colon, or semicolon.
- A word longer than six letters
- A word without letters e

// Enter your regulars verify (/.../, ["my car", "bad cats"], ["camper", "high art"]); verify (/.../, ["pop culture", "mad props"], ["plop"]); verify (/.../, ["ferret", "ferry", "ferrari"], ["ferrum", "transfer A"]); verify (/.../, ["how delicious", "spacious room"], ["ruinous", "consciousness"]); verify (/.../, ["bad punctuation."], ["escape the dot"]); verify (/.../, ["hottentottententen"], ["no", "hotten totten tenten"]); verify (/.../, ["red platypus", "wobbling nest"], ["earth bed", "learning ape"]); function verify (regexp, yes, no) (// Ignore unfinished exercises if (regexp.source == "...") return; yes.forEach (function (s) (if (! regexp.test (s)) console .log ("Not found" "+ s +" "");)); no.forEach (function (s) (if (regexp.test (s)) console.log ("Unexpected entry" "+ s +" "");));)

Quotes in text
Let's say you wrote a story and used single quotes to indicate dialogues. Now you want to replace the dialog quotes with double quotes, and keep the single quotes in abbreviations of words like aren't.

Come up with a pattern to distinguish between these two uses of quotation marks, and write a call to the replace method that performs the replacement.

Numbers again
Sequences of numbers can be found with a simple regex / \ d + /.

Write an expression that matches only JavaScript-style numbers. It should support a possible minus or plus before a number, a decimal point, and an exponential notation of 5e-3 or 1E10 - again with a possible plus or minus. Also note that numbers do not have to be before or after a dot, but a number cannot consist of a single dot. That is, .5 or 5. are valid numbers, but one dot itself is not.

// Enter the regex here. var number = /^...$/; // Tests: ["1", "-1", "+15", "1.55", ".5", "5.", "1.3e2", "1E-4", "1e + 12"] .forEach (function (s) (if (! number.test (s)) console.log ("Not found" "+ s +" "");)); ["1a", "+ -1", "1.2.3", "1 + 1", "1e4.5", ".5.", "1f5", "."]. ForEach (function (s) (if (number.test (s)) console.log ("Wrong accepted" "+ s +" "");));

Last updated: 1.11.2015

Regular Expressions represent a pattern that is used to search or modify a string. To work with regular expressions in JavaScript, an object is defined RegExp.

There are two ways to define a regular expression:

Var myExp = / hello /; var myExp = new RegExp ("hello");

The regular expression used here is pretty simple: it consists of a single word "hello". In the first case, the expression is placed between two slashes, and in the second case, the RegExp constructor is used, in which the expression is passed as a string.

RegExp methods

To determine if a regular expression matches a string, the test () method is defined in the RegExp object. This method returns true if the string matches the regular expression, and false if it doesn't.

Var initialText = "hello world!"; var exp = / hello /; var result = exp.test (initialText); document.write (result + "
"); // true initialText =" beautifull wheather "; result = exp.test (initialText); document.write (result); // false - there is no" hello "in the initialText line

The exec method works similarly - it also checks if the string matches a regular expression, only now this method returns the part of the string that matches the expression. If there is no match, then null is returned.

Var initialText = "hello world!"; var exp = / hello /; var result = exp.exec (initialText); document.write (result + "
"); // hello initialText =" beautifull wheather "; result = exp.exec (initialText); document.write (result); // null

Character groups

A regular expression does not have to be regular strings, but it can also include special regular expression syntax elements. One of these elements represents groups of characters enclosed in square brackets. For example:

Var initialText = "defenses"; var exp = / [abc] /; var result = exp.test (initialText); document.write (result + "
"); // true initialText =" city "; result = exp.test (initialText); document.write (result); // false

The expression [abc] indicates that the string must have one of three letters.

If we need to determine the presence of alphabetic characters from a certain range in a string, then we can set this range once:

Var initialText = "defenses"; var exp = / [a-z] /; var result = exp.test (initialText); document.write (result + "
"); // true initialText =" 3di0789 "; result = exp.test (initialText); document.write (result); // false

In this case, the string must contain at least one character from range a-z.

If, on the contrary, it is not necessary for the string to have only certain characters, then it is necessary to put the ^ sign in square brackets before listing the characters:

Var initialText = "defenses"; var exp = / [^ a-z] /; var result = exp.test (initialText); document.write (result + "
"); // false initialText =" 3di0789 "; exp = / [^ 0-9] /; result = exp.test (initialText); document.write (result); // true

In the first case, the string should not have only characters from the range a-z, but since the string "defenses" consists only of characters from this range, the test () method returns false, that is, the regular expression does not match the stock.

In the second case ("3di0789"), the string should not contain only numeric characters. But since the string also contains letters, the string matches the regular expression, so the test method returns true.

If necessary, we can collect combinations of expressions:

Var initialText = "home"; var exp = / [dt] o [nm] /; var result = exp.test (initialText); document.write (result); // true

The expression [dt] o [nm] indicates those strings that may contain substrings "house", "volume", "don", "tone".

Expression properties

    The global property allows you to find all substrings that match the regular expression. By default, when searching for substrings, the regular expression selects the first found substring from the string that matches the expression. Although there can be many substrings in a string that also match the expression. For this, this property is used in the form of the symbol g in expressions

    The ignoreCase property allows you to find substrings that match the regular expression, regardless of the case of the characters in the string. To do this, the symbol i is used in regular expressions

    The multiline property allows you to find substrings that match a regular expression in multiline text. To do this, the m symbol is used in regular expressions.

For example:

Var initialText = "hello world"; var exp = / world /; var result = exp.test (initialText); // false

There is no match between the string and the expression, since "World" differs from "world" in case. In this case, you need to change the regular expression by adding the ignoreCase property to it:

Var exp = / world / i;

Well, we can also use several properties at once.


2021
maccase.ru - Android. Brands. Iron. news