How to use Regular Expressions in Javascript

JavaScript defines a datatype known as a regular expression for describing and matching patterns in strings of text. RegExps are not one of the fundamental data types in JavaScript, but they have a literal syntax like numbers and strings do, so they sometimes seem like they are fundamental.

A regular expression is a pattern of characters.

Syntax : 

        
 /pattern/modifiers;        
    
        
 var str = /^b…m$/        
    

The above code defines a RegEx pattern. The pattern is: any five letter string starting with b and ending with m.

String Matched
bm No match
byuetm No match
btm No match
bwdem match

There are two ways you can create a regular expression in JavaScript.

1) Using a regular expression literal

The regular expression consists of a pattern enclosed between slashes /

        
cost str = /xyz/;        
    

Here /xyz/ is an regular expression.

2) Using the RegExp() constructor function

You can also create a regular expression by calling the RegExp() constructor Function.

        
const str = new Str('xyz');        
    

MetaCharacters

Metacharacters are characters that are interpreted in a special way by a RegEx engine. Here's a list of metacharacters:

[ ]. ^ $ * + ? { } ( ) \ |

[] - Square brackets

Expression String Matched
[abc] a 1 match
[abc] ab 2 match
[abc] abx 2 match
[abc] xyz No match
[abc] aaa 3 match

. - Period

A period matches any single character (except newline '\n').

Expression String Matched
.. x No match
.. xy 1 match
.. xyz 1 match
.. xyzw 2 match

 

^ - Caret

The caret symbol ^ is used to check if a string starts with a certain character.

Expression String Matched
^x x 1 match
^x pqr No match
^x abc No match
^x xy 1 match

 

$ - Dollar

The dollar symbol $ is used to check if a string ends with a certain character.

Expression String Matched
x$ x 1 match
x$ abx 1 match
x$ bnc No match

 

Posted in

Ankit Patel

Leave a Comment

Your email address will not be published.

Scroll to Top