CS133JS Beginning Programming: JavaScript

Regular Expressions

Topics by Week 
1. Intro to JavaScript programming6. Arrays
2. Functions, Operators and Expressions7. Objects and Object Constructors
3. Conditional Statements: if and switch8. Web Page I/O
4. Repetition: while, do while, and for9. Regular Expressions
5. Midterm Check-Point10. Review

Table of Contents

Introduction

Announcements

 

Q and A

String Methods that use Regular Expressions

match

These methods match a string against a string or a regular expression and return an array containing the matches, or null if no match is found.

 

replace

This method searches a string using another string value or a regular expression. It returns a new string with the value(s) replaced. It does not change the original string.

 

This method matches a string against a regular expression. It returns the index (position) of the first match. If no match is found, it returns -1. The method is case sensitive.

 

split

This method splits a string into an array of substrings. It returns a new array. It does not change the original string.

Note: if (" ") is used as separator, the string is split between words.

 

Using Variables in a RegExp

Regular expression literals are constant, and can not be used with variables.

You can use variables with a RegExp constructor. For example:

To insert a variable into a literal regex string (not RegExp object), just concatenate the variable into the appropriate part of the regex string. This will check to see if a string starts with the word in the variable.

 

Reference

W3Schools

String match method

String replace method

String split method


Creative Commons License Beginning JavaScript Lecture Notes by Brian Bird, are licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.