JavaScript Regular Expressions Part1 - JavaScript Tutorial 88

Опубликовано: 28 Сентябрь 2024
на канале: ChidresTechTutorials
2,071
56

Notes for You:: JavaScript Regular Expressions Part1 - JavaScript Tutorial 88

What is RegExp:
- RegExp is a built-in object, used to define a search pattern (or regular expression), which can be used to make a wide variety of tests on a given string.

Application of Regular Expressions:
- Search for a word(s) in a given string
- Find & replace a word(s) in a given string
- Perform data validations etc. etc.


1. Defining regular expression using RegExp object constructor notation:

Syntax:
var variableName = new RegExp("search pattern", ["flags"] ) ;

Ex: phone number validation
var pattern = new RegExp("^[0-9]{10}$") ;

2. Defining regular expression using RegExp literal notation:

Syntax:
var variableName = /search pattern/ [flags] ;

Ex: phone number validation
var pattern = /^[0-9]{10}$/;



JavaScript RegExp Methods:

test() Method:
- is used to test is there match or no match between regular expression and the given string.
- If there is a match then it returns true otherwise returns false.

Syntax
pattern.test(str:String):Boolean

Ex:
var phoneNumber = "1234567891";
var pattern = /^[0-9]{10}$/;
document.write(pattern.test(phoneNumber)); // true

exec() Method:
- is used to search for an occurrence(s) of a pattern in a given string.
- Returns an array with found pattern, it's index and some other extra properties otherwise returns null.

Note: exec method updates itself for the next match.

Syntax
pattern.exec(str:String):array

Example code:
var myName = "I am Javascript. I am the best. I am lovely";
var pattern = /am/g;
var rArray=[];

while( (rArray = pattern.exec(myName)) != null)
{
document.write("found word : ",rArray[0],"<br/>");
document.write("location: ",rArray.index,"<br/>");
}

Note:
- replace < with less-than symbol.
- replace > with greater-than symbol.


=========================================

Follow the link for next video:
JavaScript Tutorial 89 - Regular Expression Flags in JavaScript
   • JavaScript Regular Expressions Part2 ...  

Follow the link for previous video:
JavaScript Tutorial 87 - String Methods in JavaScript | JavaScript String Methods
   • JavaScript String Functions - JavaScr...  

=========================================

JavaScript Tutorials Playlist:-
   • JavaScript Tutorials  

=========================================
Watch My Other Useful Tutorials:-

jQuery Tutorials Playlist:-
   • jQuery Tutorials  

jQuery UI Tutorials Playlist:-
   • jQuery UI Tutorials  

Bootstrap Tutorials Playlist:-
   • Bootstrap4 Tutorials  

=========================================

► Subscribe to our YouTube channel:
   / chidrestechtutorials  

► Visit our Website:
https://www.chidrestechtutorials.com

=========================================
Hash Tags:-
#ChidresTechTutorials #JavaScript #JavaScriptTutorial