CS133JS Beginning Programming: JavaScript
| Topics by Week | |
|---|---|
| 1. Intro to JavaScript programming | 6. Arrays |
| 2. Functions, Operators and Expressions | 7. Objects and Object Constructors |
| 3. Conditional Statements: if and switch | 8. Web Page I/O |
| 4. Repetition: while, do while, and for | 9. Regular Expressions |
| 5. Midterm Check-Point | 10. Term Project and Review |
| 11. Final |
String Methods that use Regular ExpressionsmatchreplacesearchsplitUsing Variables in a RegExpReferenceW3Schools
matchThese 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.
match using a string:
let text = "Peter Piper picked a peck of pickled peppers.";let resultArray = text.match("pi");// resultArray: ["pi"], resultArray.index: 12match using regex. Note that this is more flexible, for example, we can ignore case and match globally.
text = "Peter Piper picked a peck of pickled peppers.";resultArray = text.match(/pi/ig); // ignore case// resultArray: ["Pi", "pi", pi"]replaceThis 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.
Replace a sub-string with another string:
text = "Peter Piper picked a peck of pickled peppers.";result = text.replace("peck", "pint");// result: "Peter Piper picked a pint of pickled peppers."Replace using regex:
text = "Once a duck, always a duck.";result = text.replace(/duck/g, "titan");// result: "Once a titan, always a titan."searchThis 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.
let text = "Spring is springing";let position = text.search(/spring/ig);// position: 0splitThis 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.
let text = "Are you a robot?";const outputArray = text.split(/\s/);// outputArray: ["Are", "you", "a", "robot?"]Regular expression literals are constant, and can not be used with variables.
You can use variables with a RegExp constructor. For example:
let patternString = "( is){2}";regExpObj = new RegExp(patternString, "g");let result = regExpObj.test("It depends on what the meaning of is is");// result: trueTo 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.
let word = "cat";regExpObj = new RegExp("^" + word, "i");let result = regExpObj.test("Cats are mammals.");// result: true
Beginning JavaScript Lecture Notes by Brian Bird, are licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.