0
How to create basic regular expressions in JavaScript

Open 0 Answers 19 Views Web Development

Regular expressions are sequences of characters that describe and can match patterns and strings.

There is always two parts to working with regular expressions. 

1. First, you create the expression that describes the pattern that you're looking for 

2. Second, you try and apply it to something and ask if it matches.

We are creating a variable. I'm calling it myRE for my regular expression = /hello/. 

var myRE = /hello/;

Notice it is forward slashes, not backslashes, marking this as a regular expression. This is a JavaScript shorthand for doing this. 

There is another way of doing it, which would be this.

var myRE = new RegExp("hello");

This is a longer way, but it's doing exactly the same thing, var myRE = and weuse the word new RegExp, regular expression, and feed in the string hello into it. What we are actually doing in either of these cases is creating a new regularexpression object in JavaScript. JavaScript is what is called an object oriented language, and using the word new in the second example to actually create a new object. 

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.
...