definition : Regular expression (English: Regular expression, often abbreviated as regex, RegExp, or re in code) uses a single string to describe and match a series of string search patterns that conform to a certain syntactic rule.
Regular expressions can be used for all text search and text substitution operations.
Syntax :
/pattern/modifiers;
eg
var patt =/w3cschool/i
Instance parsing:
/w3cschool/i is a regular expression.
W3cschool is a pattern (for retrieval).
i is a modifier (search is case insensitive).
Using string methods
In JavaScript, regular expressions are typically used in two string methods: Search () and replace ().
The Search () method retrieves the substring specified in the string, or retrieves a substring that matches the regular expression and returns the starting position of the substring.
The Replace () method is used to replace other characters with some characters in a string, or to replace a substring that matches a regular expression.
<p> Replace "Microsoft" for "W3cschool": </p><button onclick= "Myreplace ()" > Point me </button><p id= " Demo1 ">please visit microsoft!</p><p> search string" W3cschool "and displays the starting position of the match: </p><button onclick=" MyFunction () "> Point I </button><p id=" Demo2 "></p><script>functionMyreplace () {varstr = document.getElementById ("Demo1"). InnerHTML; vartxt = str.replace ("Microsoft", "W3cschool"); document.getElementById ("Demo1"). InnerHTML =txt;}functionMysearch () {varstr = "Visit w3cschool!"; varn = Str.search ("W3cschool"); document.getElementById ("Demo2"). InnerHTML =N;}</script>
Using the RegExp object
In JavaScript, the RegExp object is a regular expression object that has pre-defined properties and methods.
Using Test ()
The test () method is a regular expression method.
The test () method is used to detect whether a string matches a pattern and returns true if the string contains matching text, otherwise false.
The following instance is used to search for the character "E" in a string:
eg
1 var patt1=New RegExp ("E"); 2 3 document.write (Patt1.test ("The Best things on life is Free");
Using EXEC ()
The exec () method is a regular expression method.
The exec () method is used to retrieve the matching of regular expressions in a string.
The function returns an array that holds the results of the match. If no match is found, the return value is null.
The following instance is used to search for the letter "E" in the string:
1 var patt1=New RegExp ("E"); 2 3 document.write (Patt1.exec ("The Best things on life is Free");
JavaScript Basic Learning-Regular Expressions