revision:
Regular expressions are patterns used to match character combinations in strings. In JavaScript, regular expressions are also objects.
These patterns are used with the exec() and test() methods of RegExp, and with the match(), matchAll(), replace(), replaceAll(), search(), and split() methods of String.
A regular expression can be constructed in one of two ways:
using a regular expression literal, which consists of a pattern enclosed between slashes, as follows:
const re = /ab+c/;
Regular expression literals provide compilation of the regular expression when the script is loaded. If the regular expression remains constant, using this can improve performance.
calling the constructor function of the RegExp object, as follows:
const re = new RegExp("ab+c");
using the constructor function provides runtime compilation of the regular expression. Use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input.
A regular expression pattern is composed of simple characters - such as /abc/ - or a combination of simple and special characters - such as /ab*c/ or /Chapter (\d+)\.\d*/.
The last example includes parentheses, which are used as a memory device. The match made with this part of the pattern is remembered for later use.
Simple patterns are constructed of characters for which you want to find a direct match.
For example, the pattern /abc/ matches character combinations in strings only when the exact sequence "abc" occurs (all characters together and in that order).
When the search for a match requires something more than a direct match, such as finding one or more b's, or finding white space, you can include special characters in the pattern.
For example, to match a single "a" followed by zero or more "b"s followed by "c", you'd use the pattern /ab*c/: the * after "b" means "0 or more occurrences of the preceding item." In the string "cbbabbbbcdebc", this pattern will match the substring "abbbbc".
Assertions include boundaries, which indicate the beginnings and endings of lines and words, and other patterns indicating in some way that a match is possible (including look-ahead, look-behind, and conditional expressions).
^ : matches the beginning of input. If the multiline flag is set to true, also matches immediately after a line break character.
For example, /^A/ does not match the "A" in "an A", but does match the first "A" in "An A".
$ : matches the end of input. If the multiline flag is set to true, also matches immediately before a line break character.
For example, /t$/ does not match the "t" in "eater", but does match it in "eat".
\b : matches a word boundary. This is the position where a word character is not followed or preceded by another word-character, such as between a letter and a space. Note that a matched word boundary is not included in the match. In other words, the length of a matched word boundary is zero.
Examples:
/\bm/ matches the "m" in "moon".
/oo\b/ does not match the "oo" in "moon", because "oo" is followed by "n" which is a word character.
/oon\b/ matches the "oon" in "moon", because "oon" is the end of the string, thus not followed by a word character.
/\w\b\w/ will never match anything, because a word character can never be followed by both a non-word and a word character.
\B : matches a non-word boundary. This is a position where the previous and next character are of the same type: either both must be words, or both must be non-words, for example between two letters or between two spaces. The beginning and end of a string are considered non-words. Same as the matched word boundary, the matched non-word boundary is also not included in the match.
For example, /\Bon/ matches "on" in "at noon", and /ye\B/ matches "ye" in "possibly yesterday".
x(?=y) : lookahead assertion: matches "x" only if "x" is followed by "y".
For example, /Jack(?=Sprat)/ matches "Jack" only if it is followed by "Sprat".
/Jack(?=Sprat|Frost)/ matches "Jack" only if it is followed by "Sprat" or "Frost". However, neither "Sprat" nor "Frost" is part of the match results.
x(?!y) : negative lookahead assertion: matches "x" only if "x" is not followed by "y".
For example, /\d+(?!\.)/ matches a number only if it is not followed by a decimal point. /\d+(?!\.)/.exec('3.141') matches "141" but not "3".
(?<=y)x : lookbehind assertion: matches "x" only if "x" is preceded by "y".
For example, /(?<=Jack)Sprat/ matches "Sprat" only if it is preceded by "Jack".
/(?<=Jack|Tom)Sprat/ matches "Sprat" only if it is preceded by "Jack" or "Tom". However, neither "Jack" nor "Tom" is part of the match results.
(?<!y)x : negative lookbehind assertion: matches "x" only if "x" is not preceded by "y".
For example, /(?<!-)\d+/ matches a number only if it is not preceded by a minus sign.
/(?<!-)\d+/.exec('3') matches "3". /(?<!-)\d+/.exec('-3') match is not found because the number is preceded by the minus sign.
<div class="spec"> <p id="assert1"></p> <p id="assert2"></p> <p id="assert3"></p> <p id="assert4"></p> </div> <script> // Using Regex boundaries to fix buggy string. buggyMultiline = `tey, ihe light-greon apple tangs on ihe greon traa`; // 1) Use ^ to fix the matching at the beginning of the string, and right after newline. buggyMultiline = buggyMultiline.replace(/^t/gim, "h"); document.getElementById("assert1").innerHTML = (1, buggyMultiline) console.log(1, buggyMultiline); // fix 'tey' => 'hey' and 'tangs' => 'hangs' but do not touch 'traa'. // 2) Use $ to fix matching at the end of the text. buggyMultiline = buggyMultiline.replace(/aa$/gim, "ee."); document.getElementById("assert2").innerHTML = (2, buggyMultiline) console.log(2, buggyMultiline); // fix 'traa' => 'tree.'. // 3) Use \b to match characters right on border between a word and a space. buggyMultiline = buggyMultiline.replace(/\bi/gim, "t"); document.getElementById("assert3").innerHTML = (3, buggyMultiline) console.log(3, buggyMultiline); // fix 'ihe' => 'the' but do not touch 'light'. // 4) Use \B to match characters inside borders of an entity. fixedMultiline = buggyMultiline.replace(/\Bo/gim, "e"); document.getElementById("assert4").innerHTML = (4, fixedMultiline) console.log(4, fixedMultiline); // fix 'greon' => 'green' but do not touch 'on'. </script>
<div class="spec"> <p id="assert5"></p> <p id="assert6"></p> <p id="assert7"></p> </div> <script> const fruits = ["Apple", "Watermelon", "Orange", "Avocado", "Strawberry"]; // Select fruits started with 'A' by /^A/ Regex. // Here '^' control symbol used only in one role: Matching beginning of an input. const fruitsStartWithA = fruits.filter((fruit) => /^A/.test(fruit)); document.getElementById("assert5").innerHTML = fruitsStartWithA; console.log(fruitsStartWithA); // [ 'Apple', 'Avocado' ] const fruitsStartWithNotA = fruits.filter((fruit) => /^[^A]/.test(fruit)); document.getElementById("assert6").innerHTML = fruitsStartWithNotA; console.log(fruitsStartWithNotA); // [ 'Watermelon', 'Orange', 'Strawberry' ] const fruitsWithDescription = ["Red apple", "Orange orange", "Green Avocado"]; // Select descriptions that contains 'en' or 'ed' words endings: const enEdSelection = fruitsWithDescription.filter((descr) => /(en|ed)\b/.test(descr), ); document.getElementById("assert7").innerHTML = enEdSelection; console.log(enEdSelection); // [ 'Red apple', 'Green Avocado' ] </script>
Pattern modifiers (aka flags) are placed directly after the regular expression.
For example, if you want to search for a pattern in a case-insensitive manner, you can use the "i" modifier, like this: /pattern/i.
Modifiers are used to perform case-insensitive and global searches.
Syntax: /pattern/modifier(s);
Example: pattern modifiers
<p id="modif1"></p> <script> let text = "Visit my website"; let pattern = /my website/i; let result_1 = text.match(pattern); document.getElementById("modif1").innerHTML = result_1; </script>
In JavaScript, a regular expression text search can be done with different methods. With a pattern as a regular expression, these are the most common methods:
text.match(pattern)
text.search(pattern)
pattern.exec(text)
pattern.test(text)
deprecated
Syntax: new RegExp("regexp", "i") or /regexp/i
Example - i
<div class="spec"> <p>Click the button to do a case-insensitive search for "my website" in a string.</p> <button onclick="myFunction1()">Try it</button><br><br> <a id="modif2"></a><br> <a id="modif2a"></a><br> <a id="modif2b"></a><br> <a id="modif2c"></a><br> </div> <script> function myFunction1() { var str = "Visit my website"; var patt1 = /my website/i; var result = str.match(patt1); document.getElementById("modif2").innerHTML = str + " : " + result; } let text_aa = "Visit my website"; let pattern_aa = /my website/i; let result_aa = pattern_aa.exec(text_aa); document.getElementById("modif2a").innerHTML = text_aa + " -> " + result_aa; let result_ab = pattern_aa.test(text_aa); document.getElementById("modif2b").innerHTML = text_aa + " -> " + result_ab; let result_ac = text_aa.match(pattern_aa); document.getElementById("modif2c").innerHTML = text_aa + " -> " + result_ac; </script>
Syntax: new RegExp("regexp", "g") or /regexp/g
The "g modifier" is used to perform a global match (find all matches rather than stopping after the first match).
To perform a global, case-insensitive search, use this modifier together with the "i" modifier. Use the global property to specify whether or not the "g modifier" is set.
example
<div class="spec"> <p>Click the button to do a global search for "is" in a string.</p> <button onclick="myFunction()">Try it</button><br> <a id="modif3"></a><br><br> <a id="modif3a"></a><br> <a id="modif3b"></a><br> <a id="modif3c"></a><br> </div> <script> function myFunction() { var str = "Is this all there is?"; var patt1 = /is/g; var result = str.match(patt1); document.getElementById("modif3").innerHTML = str + " : " + result; } let text_bb = "Is this true? Is this all there is?"; let pattern_bb = /is/g; let result_bb = text_bb.match(pattern_bb); document.getElementById("modif3a").innerHTML = text_bb + " -> " + result_bb; let result_bc = pattern_bb.exec(text_bb); document.getElementById("modif3b").innerHTML = text_bb + " -> " + result_bc; let result_bd = pattern_bb.test(text_bb); document.getElementById("modif3c").innerHTML = text_bb + " -> " + result_bd;
<div class="spec"> <p>Click the button to check whether or not the "g" and "i" modifiers are set.</p> <button onclick="myFunction2()">Try it</button><br> <a id="modif4"></a><br><br> <a id="modif4a"></a><br> <a id="modif4b"></a><br> <a id="modif4c"></a><br> <a id="modif4d"></a><br> </div> <script> function myFunction2() { var str = "Interested in my website on Internet!"; var patt1 = /in/gi; var res = str.match(patt1); document.getElementById("modif4").innerHTML = str + ": " + res; } let text_cc = "Is this true? Is this all there is?"; let result_cc = /is/gi.exec(text_cc); document.getElementById("modif4a").innerHTML = text_cc + " -> " + result_cc; let result_cd = /is/gi.test(text_cc); document.getElementById("modif4b").innerHTML = text_cc + " -> " + result_cd; let result_ce = text_cc.match(/is/gi); document.getElementById("modif4c").innerHTML = text_cc + " -> " + result_ce; </script>
You can use the global property to check if the g modifier is set.
example - check g
<p id="global1" clas="=spec"></p> <script> let pattern_g = /W3S/g; let result_g = pattern_g.global; document.getElementById("global1").innerHTML = result_g; </script>
Syntax: new RegExp("regexp", "m") or /regexp/m
It only affects the behavior of start ^ and end $. ^ specifies a match at the start of a string. $ specifies a match at the end of a string. With the "m" set, ^ and $ also match at the beginning and end of each line.
The "m" modifier is case-sensitive and not global. To perform a global, case-insensitive search, use "m" with "g" and "i".
The multiline property specifies whether or not the "m modifier" is set. This property returns true if the "m" modifier is set, otherwise it returns false
Example - m
<div class="spec"> <p>Click the button to check whether or not the "m" modifier is set.</p> <button onclick="myFunction2A()">Try it</button><br> <a id="modif5"></a><br> <a id="modif5a"></a><br> <a id="modif5b"></a><br> <a id="modif5c"></a><br> <a id="modif5d"></a><br> </div> <script> function myFunction2A() { var str = "Visit my website!"; var patt1 = /my/m; var resu = patt1.multiline; document.getElementById("modif5").innerHTML = resu; } let text_dd = `Is this all there is` let pattern_dd = /^is/m; let result_dd = text_dd.match(pattern_dd); document.getElementById("modif5a").innerHTML = "/^is/m :" + result_dd; let pattern_de = /^is/gm; let result_de = text_dd.match(pattern_de); document.getElementById("modif5b").innerHTML = "/^is/gm :" +result_de; let pattern_df = /^is/gmi; let result_df = text_dd.match(pattern_df); document.getElementById("modif5c").innerHTML = "/^is/gmi :" +result_df; let pattern_dg = /is$/gm; let result_dg = text_dd.match(pattern_dg); document.getElementById("modif5d").innerHTML = "/is$/gm :" +result_dg;
The multiline property specifies whether or not the "m modifier" is set. This property returns true if the "m" modifier is set, otherwise it returns false
example
<p id="multiline1"></p> <script> let text_ee = "Visit W3Schools!"; let pattern_ee = /W3S/gi; let result_ee = pattern_ee.multiline; document.getElementById("multiline1").innerHTML = result_ee;
Syntax: new RegExp("[abc]") or simply: /[abc]/
Syntax with modifiers: new RegExp("[abc]", "g") or simply: /[abc]/g
Brackets can define single characters, groups, or character spans:
[abc] : any of the characters a, b, or c;
[A-Z] : any character from uppercase A to uppercase Z;
[a-z] : any character from lowercase a to lowercase z;
[A-z] : any character from uppercase A to lowercase z
<div class="spec"> <p>Click the button to do a global, case-insensitive search for the character-span [a-s].</p> <button onclick="myFunction7()">Try it</button><br> <a id="brack5"></a> </div> <script> function myFunction7() { var str = "I Scream For Ice Cream, is that OK?!"; var patt1 = /[a-s]/gi; var result = str.match(patt1); document.getElementById("brack5").innerHTML = str + " : " + result; } </script>
<div class="spec"> <p>Click the button to do a global search for the character "h" in a string.</p> <button onclick="myFunction3()">Try it</button><br> <a id="brack1"></a> </div> <script> function myFunction3() { var str = "Is this all there is?"; var patt1 = /[h]/g; var result = str.match(patt1); document.getElementById("brack1").innerHTML = str + " : " + result; } </script>
<div class="spec"> <p>Click the button to do a global search for the characters "i" and "s" in a string.</p> <button onclick="myFunction4()">Try it</button><br> <a id="brack2"></a> </div> <script> function myFunction4() { var str = "Do you know if this is all there is?"; var patt1 = /[is]/gi; var result = str.match(patt1); document.getElementById("brack2").innerHTML = str + " : " + result; } </script>
<div class="spec"> <a id="bracket1"></a><br> <a id="bracket2"></a><br> <a id="bracket3"></a> <br> </div> <script> let text_brack = "Do you know if this is all there is?"; let pattern_brack = /[is]/gi; let result_brack = text_brack.match(pattern_brack); document.getElementById("bracket1").innerHTML = text_brack + "-> " + result_brack; let pattern_brack1 = /[h]/g; let result_brack1 = text_brack.match(pattern_brack1); document.getElementById("bracket2").innerHTML = text_brack + " -> " + result_brack1; let pattern_brack2 = /[a-h]/g; let result_brack2 = text_brack.match(pattern_brack2); document.getElementById("bracket3").innerHTML = text_brack + " -> " + result_brack2;
Syntax: new RegExp("[^xyz]") or simply: /[^xyz]/
Syntax with modifiers: new RegExp("[^xyz]", "g") or simply: /[^xyz]/g
Brackets can define single characters, groups, or character spans:
[^abc] : not any of the characters a, b, or c;
[^A-Z] : not any character from uppercase A to uppercase Z;
[^a-z] : not any character from lowercase a to lowercase z;
[^A-z] : not any character from uppercase A to lowercase z
<div class="spec"> <p>Click the button to do a global, case-insensitive search for characters not in the span.</p> <button onclick="myFunction8()">Try it</button><br> <a id="brack6"></a> </div> <script> function myFunction8() { var str = "I Scream For Ice Cream, is that OK?!"; var patt1 = /[^a-m]/gi; var result = str.match(patt1); document.getElementById("brack6").innerHTML = str + " : " + result; } </script>
<div class="spec"> <a id="bracket4"></a><br> <a id="bracket5"></a><br> <a id="bracket6"></a> <br> </div> <script> let text_brack10 = "Do you know if this is all there is?"; let pattern_brack10 = /[^h]/g; let result_brack10 = text_brack10.match(pattern_brack10); document.getElementById("bracket4").innerHTML = text_brack10 + "-> " + result_brack10; let pattern_brack11 = /[^is]/gi; let result_brack11 = text_brack10.match(pattern_brack11); document.getElementById("bracket5").innerHTML = text_brack10 + " -> " + result_brack11; let pattern_brack12 = /[^a-p]/g; let result_brack12 = text_brack.match(pattern_brack12); document.getElementById("bracket6").innerHTML = text_brack10 + " -> " + result_brack12; </script>
Syntax: new RegExp("[0-9]") or simply: /[0-9]/
Syntax with modifiers: new RegExp("[0-9]", "g") or simply: /[0-9]/g
The [0-9] expression is used to find any character between the brackets. The digits inside the brackets can be any numbers or span of numbers from 0 to 9. Use the [^0-9] expression to find any character that is NOT a digit.
example
<div class="spec"> <a id="bracket7"></a><br> <a id="bracket8"></a> </div> <script> let text20 = "123456789"; let pattern20 = /[1-4]/g; let result20 = text20.match(pattern20); document.getElementById("bracket7").innerHTML = text20 + " -> " + result20; let text21 = "12121212"; let pattern21 = /[1]/g; let result21 = text21.match(pattern21); document.getElementById("bracket8").innerHTML = text21 + " -> " + result21; </script>
Syntax: new RegExp("[^0-9]") or simply: /[^0-9]/
Syntax with modifiers: new RegExp("[^0-9]", "g") or simply: /[^0-9]/g
The [^0-9] expression is used to find any character that is NOT a digit. The digits inside the brackets can be any numbers or span of numbers from 0 to 9. Use the [0-9] expression to find any character between the brackets that is a digit.
example
<div class="spec"> <a id="bracket7"></a><br> <a id="bracket8"></a> </div> <script> let text20 = "123456789"; let pattern20 = /[1-4]/g; let result20 = text20.match(pattern20); document.getElementById("bracket7").innerHTML = text20 + " -> " + result20; let text21 = "12121212"; let pattern21 = /[1]/g; let result21 = text21.match(pattern21); document.getElementById("bracket8").innerHTML = text21 + " -> " + result21; </script>
Syntax: new RegExp("[A-z]") or simply: /[A-z]/
Syntax with modifiers: new RegExp("[A-z]", "g") or simply: /[A-z]/g
<div class="spec"> <p>Click the button to do a global search for the character-span [A-h] in a string.</p> <button onclick="myFunction5()">Try it</button><br> <a id="brack3"></a> </div> <script> function myFunction5() { var str = "Is this all there is? Yes, of course"; var patt1 = /[A-h]/g; var result = str.match(patt1); document.getElementById("brack3").innerHTML = str + " : " + result; } </script>
<div class="spec"> <p style="margin-left: 3vw;">Click the button to do a global search for any character from uppercase A to uppercase E.</p> <button style="margin-left: 4vw;" onclick="myFunction6()">Try it</button><br> <a id="brack4"></a> </div> <script> function myFunction6() { var str = "I SCREAM FOR ICE CREAM!"; var patt1 = /[A-E]/g; var result = str.match(patt1); document.getElementById("brack4").innerHTML = str + " : " + result; } </script>
Syntax: new RegExp("[a|b|c]") or simply: /[a|b|c]/
Syntax with modifiers: new RegExp("[a|b|c]", "g") or simply: /[a|b|c]/g
The alternatives can be of any characters.
example
<div class="spec"> <p style="margin-left: 3vw;">Click the button to find any of the chosen characters.</p> <button style="margin-left: 4vw;" onclick="myFunction9()">Try it</button><br> <a id="brack7"></a> </div> <script> function myFunction9() { var str = "I Scream For Ice Cream, is that OK?!"; var patt1 = /[a|d|m]/gi; var result = str.match(patt1); document.getElementById("brack7").innerHTML = str + " : " + result; } </script>
<div class="spec"> <a id="bracket11"></a><br> <a id="bracket12"></a> </div> <script> let text40 = "re, green, red, green, gren, gr, blue, yellow"; let pattern40 = /(red|green)/g; let result40 = text40.match(pattern40); document.getElementById("bracket11").innerHTML = text40 + " -> " + result40; let text41 = "01234567890123456789"; let pattern41 = /(0|5|7)/g; let result41 = text41.match(pattern41); document.getElementById("bracket12").innerHTML = text41 + " -> " + result41 </script>
Syntax: new RegExp("regexp.") or simply: /regexp./
Syntax with modifiers: new RegExp("regexp.", "g") or simply: /regexp./g
example
<div class="spec"> <p>Click the button to do a global search for "h.t" in a string.</p> <button onclick="metaFunction()">Try it</button><br> <a id="meta"></a> </div> <script> function metaFunction() { var str = "That's hot!"; var patt1 = /h.t/g; var result = str.match(patt1); document.getElementById("meta").innerHTML = str + " : " + result; } </script>
Syntax: new RegExp("\\w") or simply: /\w/
Syntax with modifiers: new RegExp("\\w", "g") or simply: /\w/g
This includes a character from a-z, A-Z, 0-9, as well as the _ (underscore) character.
example
<div class="spec"> <p>Click the button to do a global search for word characters in a string.</p> <button onclick="metaFunction1()">Try it</button><br> <a id="meta1"></a> </div> <script> function metaFunction1() { var str = "Give 100% or _more!"; var patt1 = /\w/g; var result = str.match(patt1); document.getElementById("meta1").innerHTML = str + " : " + result; } </script>
Syntax: new RegExp("\\W") or simply: /\W/
Syntax with modifiers: new RegExp("\\W", "g") or simply: /\W/g
A word character is a character from a-z, A-Z, 0-9, including the _ (underscore) character.
example
<div class="spec"> <p>Click the button to do a global search for non-word characters in a string.</p> <button onclick="metaFunction2()">Try it</button><br> <a id="meta2"></a> </div> <script> function metaFunction2() { var str = "Give 100%!"; var patt1 = /\W/g; var result = str.match(patt1); document.getElementById("meta2").innerHTML = str + " : " + result; } </script>
Syntax: new RegExp("\\d") or simply: /\d/
Syntax with modifiers: new RegExp("\\d", "g") or simply: /\d/g
example
<div class="spec"> <p>Click the button to do a global search for digits in a string.</p> <button onclick="metaFunction3()">Try it</button><br> <a id="meta3"></a> </div> <script> function metaFunction3() { var str = "Give 100%!"; var patt1 = /\d/g; var result = str.match(patt1); document.getElementById("meta3").innerHTML = str + " : " + result; } </script>
Syntax: new RegExp("\\D") or simply: /\D/
Syntax with modifiers: new RegExp("\\D", "g") or simply: /\D/g
example
<div class="spec"> <p>Click the button to do a global search for non-digit characters in a string.</p> <button onclick="metaFunction4()">Try it</button><br> <a id="meta4"></a> </div> <script> function metaFunction4() { var str = "Give 100%!"; var patt1 = /\D/g; var result = str.match(patt1); document.getElementById("meta4").innerHTML = str + " : " + result; } </script>
Syntax: new RegExp("\\s") or simply: /\s/
Syntax with modifiers: new RegExp("\\s", "g") or simply: /\s/g
Whitespace characters can be a space character, a tab character, a carriage return character, a new line character, a vertical tab character, a form feed character.
example
Click the button to do a global search for whitespace characters in a string.
<div class="spec"> <p>Click the button to do a global search for whitespace characters in a string.</p> <button onclick="metaFunction5()">Try it</button><br> <aid="meta5"></a> </div> <script> function metaFunction5() { var str = "Is this all there is?"; var patt1 = /\s/g; var result = str.match(patt1); document.getElementById("meta5").innerHTML = str + " : " + result; } </script>
Syntax: new RegExp("\\S") or simply: /\S/
Syntax with modifiers: new RegExp("\\S", "g") or simply: /\S/g
A whitespace character can be: a space character, a tab character, a carriage return character, a new line character, a vertical tab character, a form feed character.
example
<div class="spec"> <p>Click the button to search for non-whitespace characters in a string.</p> <button onclick="metaFunction6()">Try it</button><br> <a id="meta6"></a> </div> <script> function metaFunction6() { var str = "Is this all there is?"; var patt1 = /\S/g; var result = str.match(patt1); document.getElementById("meta6").innerHTML = str + " : " + result; } </script>
Syntax: new RegExp("\\bregexp") or simply: /\bregexp/
Syntax with modifiers: new RegExp("\\bregexp", "g") or simply: /\bregexp/g
Search for the pattern at the beginning of a word like this: \bLO.
Search for the pattern at the end of a word like this: LO\b.
If no match is found, it returns null.
example
Search for the characters "LO"in the beginning of a word in the phrase: "HELLO, LOOK AT YOU!"
Found in position:
<div class="spec"> <p>Search for the characters "LO"in the <strong>beginning</strong> of a word in the phrase: "HELLO, LOOK AT YOU!"</p> <p>Found in position: <span style="color:red" id="meta7"></span></p> </div> <script> var str = "HELLO, LOOK AT YOU!"; var patt1 = /\bLO/; var result = str.search(patt1); document.getElementById("meta7").innerHTML = result; </script>
Search for the characters "LO"in the end of a word in the phrase: "HELLO, LOOK AT YOU!"
Found in position:
<div class="spec"> <p>Search for the characters "LO"in the <strong>end </strong> of a word in the phrase: "HELLO, LOOK AT YOU!"</p> <p style="margin-left: 3vw;">Found in position: <span style="color:red" id="meta8"></span></p> </div> <script> var str = "HELLO, LOOK AT YOU!"; var patt1 = /LO\b/; var result = str.search(patt1); document.getElementById("meta8").innerHTML = result; </script>
Syntax: new RegExp("\\Bregexp") or simply: /\Bregexp/
Syntax with modifiers: new RegExp("\\Bregexp", "g") or simply: /\Bregexp/g
Search for the pattern NOT at the beginning of a word like this: \BLO.
Search for the pattern NOT at the end of a word like this: LO\B.
If no match is found, it returns null.
example
Search for the characters "LO"in the phrase: "HELLO, LOOK AT YOU!" and return the first position where it is present, but NOT in the beginning of a word
Found in position:
<div class="spec"> <>Search for the characters "LO"in the phrase: "HELLO, LOOK AT YOU!" and return the first position where it is present, but NOT in the <strong>beginning</strong> of a word </p> <p>Found in position: <span style="color: red" id="meta9"></span></p> </div> <script> var str = "HELLO, LOOK AT YOU!"; var patt1 = /\BLO/; var result = str.search(patt1); document.getElementById("meta9").innerHTML = result; </script>
Search for the characters "LO"in the phrase: "HELLO, LOOK AT YOU!" and return the first position where it is present, but NOT in the end of a word
Found in position:
<div class="spec"> <p>Search for the characters "LO"in the phrase: "HELLO, LOOK AT YOU!" and return the first position where it is present, but NOT in the <strong>end</strong> of a word </p> <p>Found in position: <span style="color: red" id="meta10"></span></p> </div> <script> var str = "HELLO, LOOK AT YOU!"; var patt1 = /LO\B/; var result = str.search(patt1); document.getElementById("meta10").innerHTML = result; </script>
Syntax: new RegExp("\\0") or simply: /\0/
\0 returns the position where the NUL character was found. If no match is found, it returns -1.
example
<div class="spec"> <p style="margin-left: 3vw;">Click the button to return the position where the NUL character was found in a string.</p> <button style="margin-left: 4vw;" onclick="metaFunction7()">Try it</button> <a id="meta11"></a> </div> <script> function metaFunction7() { var str = "Visit W3Schools.\0Learn JavaScript."; var patt1 = /\0/; var result = str.search(patt1); document.getElementById("meta11").innerHTML = str + " : " + result; } </script>
Syntax: new RegExp("\\n") or simply: /\n/
\n returns the position where the newline character was found. If no match is found, it returns -1.
example
<div class="spec"> <p>Click the button to return the position where the newline character was found in a string.</p> <button onclick="metaFunction8()">Try it</button> <a id="meta12"></a> </div> <script> function metaFunction8() { var str = "Visit W3Schools.\nLearn JavaScript."; var patt1 = /\n/; var result = str.search(patt1); document.getElementById("meta12").innerHTML = str + " : " + result; } </script>
Syntax: new RegExp("\\f") or simply: /\f/
\f returns the position where the form feed character was found. If no match is found, it returns -1.
example
<div class="spec"> <p>Click the button to return the position where the form feed character was found in a string.</p> <button onclick="metaFunction9()"> Try it</button> <a id="meta13"></a> </div> <script> function metaFunction9() { var str = "Visit W3Schools.\fLearn JavaScript."; var patt1 = /\f/; var result = str.search(patt1); document.getElementById("meta13").innerHTML = str + " : " + result; } </script>
Syntax: new RegExp("\\r") or simply: /\r/
\r returns the position where the carriage return character was found. If no match is found, it returns -1.
example
<div class="spec"> <p>Click the button to return the position where the carriage return character was found in a string.</p> <button onclick="metaFunction10()"> Try it</button> <a id="meta14"></a> </div> <script> function metaFunction10() { var str = "Visit W3Schools.\rLearn JavaScript."; var patt1 = /\r/; var result = str.search(patt1); document.getElementById("meta14").innerHTML = str + " : " + result; } </script>
Syntax: new RegExp("\\t") or simply: /\t/
\t returns the position where the tab character was found. If no match is found, it returns -1.
example
<div> <p>Click the button to return the position where the tab character was found in a string.</p> <button onclick="metaFunction11()"> Try it</button> <a id="meta15"></a> </div> <script> function metaFunction11() { var str = "Visit W3Schools.\tLearn JavaScript."; var patt1 = /\t/; var result = str.search(patt1); document.getElementById("meta15").innerHTML = str + " : " + result; } </script>
Syntax: new RegExp("\\v") or simply: /\v/
\v returns the position where the vertical tab character was found. If no match is found, it returns -1.
example
<div class="spec"> <p>Click the button to return the position where the vertical tab character was found in a string.</p> <button onclick="metaFunction12()"> Try it</button> <a id="meta16"></a> </div> <script> function metaFunction12() { var str = "Visit W3Schools.\vLearn JavaScript."; var patt1 = /\v/; var result = str.search(patt1); document.getElementById("meta16").innerHTML = str + " : " + result; } </script>
Syntax: new RegExp("\\xxx") or simply: /\xxx/
If no match is found, it returns null.
example
<div class="spec"> <p>Click the button to do a global search for octal number 127 (W) in a string.</p> <button onclick="metaFunction13()"> Try it</button> <a id="meta17"></a> </div> <script> function metaFunction13() { var str = "Visit W3Schools. Hello World!"; var patt1 = /\127/g; var result = str.match(patt1); document.getElementById("meta17").innerHTML = str + " : " + result; } </script>
Syntax: new RegExp("\\xdd") or simply: /\xdd/
If no match is found, it returns null.
example
<div class="spec"> <p>Click the button to do a global search for the hexadecimal number 57 (W) in a string.</p> <button onclick="metaFunction14()"> Try it</button> <a id="meta18"></a> </div> <script> function metaFunction14() { var str = "Visit W3Schools. Hello World!"; var patt1 = /\x57/g; var result = str.match(patt1); document.getElementById("meta18").innerHTML = str + " : " + result; } </script>
Syntax: new RegExp("\\udddd") or simply: /\udddd/
Syntax with modifiers: new RegExp("\\udddd", "g") or simply: /\udddd/g
If no match is found, it returns null.
example
<div class="spec"> <p>Click the button to do a global search for the hexadecimal number 0057 (W) in a string.</p> <button onclick="metaFunction18()"> Try it</button> <a id="meta19"></a> </div> <script> function metaFunction18() { var str = "Visit W3Schools. Hello World!"; var patt1 = /\u0057/g; var result = str.match(patt1); document.getElementById("meta19").innerHTML = str + " : " + result; } </script>
Quantifiers match a number of instances of a character, group, or character class in a string.
Syntax: new RegExp("n+") or simply: /n+/
Syntax with modifiers: new RegExp("n+", "g") or simply: /n+/g
example
<div class="spec"> <p>Click the button to do a global search for at least one "o" in a string.</p> <button onclick="Func()">Try it</button><br> <a id="quant"></a> </div> <script> function Func() { var str = "Hellooo World! Hello good-looking township!"; var patt1 = /o+/g; var result = str.match(patt1); document.getElementById("quant").innerHTML = str + " : " + result; } </script>
Syntax: new RegExp("n*") or simply: /n*/
Syntax with modifiers: new RegExp("n*", "g") or simply: /n*/g
example
<div class="spec"> <p>Click the button to do a global search for an "l", followed by zero or more "o" characters.</p> <button onclick="Func1()">Try it</button><br> <a id="quant1"></a> </div> <script> function Func1() { var str = "Hellooo World! Hello good-looking township!"; var patt1 = /lo*/g; var result = str.match(patt1); document.getElementById("quant1").innerHTML = str + " : " + result; } </script>
Syntax: new RegExp("n?") or simply: /n?/
Syntax with modifiers: new RegExp("n?", "g") or simply: /n?/g
example
<div class="spec"> <p>Click the button to do a global search for a "1", followed by zero or one "0" characters.</p> <button onclick="Func2()">Try it</button><br> <a id="quant2"></a> </div> <script> function Func2() { var str = "1, 100 or 1000?"; var patt1 = /10?/g; var result = str.match(patt1); document.getElementById("quant2").innerHTML = str + " : " + result; } </script>
Syntax: new RegExp("n{X}") or simply: /n{X}/
Syntax with modifiers: new RegExp("n{X}", "g") or simply: /n{X}/g
The n{X} quantifier matches any string that contains a sequence of X n's. X must be a number.
example
<div class="spec"> <p>Click the button to do a global search for a substring that contains a sequence of four digits.</p> <button onclick="Func3()">Try it</button><br> <a id="quant3"></a> </div> <script> function Func3() { var str = "100, 1000 or 10000?"; var patt1 = /\d{4}/g; var result = str.match(patt1); document.getElementById("quant3").innerHTML = str + " : " + result; }
Syntax: new RegExp("n{X,Y}") or simply: /n{X,Y}/
Syntax with modifiers: new RegExp("n{X,Y}", "g") or simply: /n{X,Y}/g
The n{X,Y} quantifier matches any string that contains a sequence of X to Y n's. X and Y must be a number.
example
<div class="spec"> <p">Click the button to global search for a substring that contains a sequence of three to four digits.</p> <button onclick="Func4()">Try it</button><br> <a id="quant4"></a> </div> <script> function Func4() { var str = "100, 1000 or 10000?"; var patt1 = /\d{3,4}/g; var result = str.match(patt1); document.getElementById("quant4").innerHTML = str + " : " + result; } </script>
Syntax: new RegExp("n{X,}") or simply: /n{X,}/
Syntax with modifiers: new RegExp("n{X,}", "g") or simply: /n{X,}/g
The n{X,} quantifier matches any string that contains a sequence of at least X n's. X must be a number.
example
<div class="spec"> <p>Click the button to global search for a substring that contains a sequence of three to four digits.</p> <button onclick="Func5()">Try it</button><br> <a id="quant5"></a> </div> <script> function Func5() { var str = "100, 1000 or 10000?"; var patt1 = /\d{3,}/g; var result = str.match(patt1); document.getElementById("quant5").innerHTML = str + " : " + result; } </script>
Syntax: new RegExp("n$") or simply: /n$/
Syntax with modifiers: new RegExp("n$", "g") or simply: /n$/g
The n$ quantifier matches any string with n at the end of it. Tip: Use the ^n quantifier to match any string with n at the BEGINNING of it.
example
<div class="spec"> <p>Click the button to global search for "is" at the end of a string.</p> <button onclick="Func6()">Try it</button><br> <a id="quant6"></a> </div> <script> function Func6() { var str = "Is this his"; var patt1 = /\is$/g; var result = str.match(patt1); document.getElementById("quant6").innerHTML = str + " : " + result; } </script>
Syntax: new RegExp("n^") or simply: /n^/
Syntax with modifiers: new RegExp("n^", "g") or simply: /n^/g
The ^n quantifier matches any string with n at the beginning of it. Tip: Use the n$ quantifier to match any string with n at the END of it.
example
<div class="spec"> <p>Click the button to do a global search for "Is" at the beginning of a string.</p> <button onclick="Func7()">Try it</button><br> <a id="quant7"></a> </div> <script> function Func7() { var str = "Is this his"; var patt1 = /^Is/g; var result = str.match(patt1); document.getElementById("quant7").innerHTML = str + " : " + result; } </script>
Syntax: new RegExp("regexp(?=n)") or simply: /regexp(?=n)/
Syntax with modifiers: new RegExp("regexp(?=n)", "g") or simply: /regexp(?=n)/g
The ?=n quantifier matches any string that is followed by a specific string n. Tip: Use the ?!n quantifier to match any string that is NOT followed by a specific string n.
example
<div class="spec"> <p>Click the button to global search for "is" followed by " all".</p> <button onclick="Func8()">Try it</button><br> <a id="quant8"></a> </div> <script> function Func8() { var str = "Is this all there is"; var patt1 = /is(?= all)/; var result = str.match(patt1); document.getElementById("quant8").innerHTML = str + " : " + result; } </script>
Syntax: new RegExp("regexp(?!n)") or simply: /regexp(?!n)/
Syntax with modifiers: new RegExp("regexp(?!n)", "g") or simply: /regexp(?!n)/g
The ?!n quantifier matches any string that is not followed by a specific string n. Tip: Use the ?=n quantifier to match any string that IS followed by a specific string n.
example
<div class="spec"> <p>Click the button to do a global, case insensitive search for "is" not followed by " all"</p> <button onclick="Func9()">Try it</button><br> <a id="quant9"></a> </div> <script> function Func9() { var str = "Is this all there is"; var patt1 = /is(?! all)/gi; var result = str.match(patt1); document.getElementById("quant9").innerHTML = str + " : " + result; } </script>
let str = "We will, we will rock you"; alert( str.match(/we/gi) ); // We,we (an array of 2 substrings that match) let str = "We will, we will rock you"; let result = str.match(/we/i); // without flag g alert( result[0] ); // We (1st match) alert( result.length ); // 1 // div: alert( result.index ); // 0 (position of the match) alert( result.input ); // We will, we will rock you (source string) let matches = "JavaScript".match(/HTML/); // = null if (!matches.length) { // Error: Cannot read property 'length' of null alert("Error in the line above"); } let matches = "JavaScript".match(/HTML/) || []; if (!matches.length) { alert("No matches"); // now it works }
// no flag g alert( "We will, we will".replace(/we/i, "I") ); // I will, we will // with flag g alert( "We will, we will".replace(/we/ig, "I") ); // I will, I will alert( "I love HTML".replace(/HTML/, "$& and JavaScript") ); // I love HTML and JavaScript
let str = "I love JavaScript"; let regexp = /LOVE/i; alert( regexp.test(str) ); // true
// find [t or m], and then "op" alert( "Mop top".match(/[tm]op/gi) ); // "Mop", "top" // find "V", then [o or i], then "la" alert( "Voila".match(/V[oi]la/) ); // null, no matches
alert( "Exception 0xAF".match(/x[0-9A-F][0-9A-F]/g) ); // xAF let regexp = /[\p{Alpha}\p{M}\p{Nd}\p{Pc}\p{Join_C}]/gu; let str = `Hi 你好 12`; // finds all letters and digits: alert( str.match(regexp) ); // H,i,你,好,1,2
alert( "[email protected]".match(/[^\d\sA-Z]/gi) ); // @ and . // No need to escape let regexp = /[-().^+]/g; alert( "1 + 2 - 3".match(regexp) ); // Matches +, - // Escaped everything let regexp = /[\-\(\)\.\^\+]/g; alert( "1 + 2 - 3".match(regexp) ); // also works: +, -
alert( '𝒳'.match(/[𝒳𝒴]/) ); // shows a strange character, like [?] // (the search was performed incorrectly, half-character returned) for(let i=0; i<'𝒳𝒴'.length; i++) { alert('𝒳𝒴'.charCodeAt(i)); // 55349, 56499, 55349, 56500 }; alert( '𝒳'.match(/[𝒳𝒴]/u) ); // 𝒳 𝒳'.match(/[𝒳-𝒴]/); // Error: Invalid regular expression // look for characters from 𝒳 to 𝒵 alert( '𝒴'.match(/[𝒳-𝒵]/u) ); // 𝒴
let str = "+7(903)-123-45-67"; let regexp = /\d/; alert( str.match(regexp) ); // 7 let str = "+7(903)-123-45-67"; let regexp = /\d/g; alert( str.match(regexp) ); // array of matches: 7,9,0,3,1,2,3,4,5,6,7 // let's make the digits-only phone number of them: alert( str.match(regexp).join('') ); // 79031234567 let str = "Is there CSS4?"; let regexp = /CSS\d/ alert( str.match(regexp) ); // CSS4 alert( "I love HTML5!".match(/\s\w\w\w\w\d/) ); // ' HTML5'
let str = "+7(903)-123-45-67"; alert( str.replace(/\D/g, "") ); // 79031234567
alert( "Z".match(/./) ); // Z let regexp = /CS.4/; alert( "CSS4".match(regexp) ); // CSS4 alert( "CS-4".match(regexp) ); // CS-4 alert( "CS 4".match(regexp) ); // CS 4 (space is also a character) alert( "CS4".match(/CS.4/) ); // null, no match because there's no character for the dot
alert( "A\nB".match(/A.B/) ); // null (no match) alert( "A\nB".match(/A.B/s) ); // A\nB (match!)
let regexp = /".+?"/g; let str = 'a "witch" and her "broom" is one'; alert( str.match(regexp) ); // "witch", "broom" let regexp = /"[^"]+"/g; let str = 'a "witch" and her "broom" is one'; alert( str.match(regexp) ); // "witch", "broom"