- slide 1 of 4
The variable 'newstr' will now contain the string "I just went to Catalina and bought a new auto".
What if, instead, we wanted to replace all of the words that began with the letter 'C' with auto? We can't specify that with a string for the first argument of replace. Instead, we will have to use regular expressions.
- slide 2 of 4
Wildcards and Regular Expressions
Continuing our example from above, if we wanted to write a regular expression that matched any word that started with the letter c, we would write the following: /\bc[A-Za-z0-9]*/g.
The first character, /, signifies that we are starting a regular expression. \b indicates that we want to match the beginning of a word. The c tells the regular expression compiler which letter we are looking for. [A-Za-z0-9]* says to allow zero or more characters or digits after the letter c. The next forward slash signifies the end of the regular expression, and the g indicates that we want to replace all instances that are matched.
Our new code would read as follows:
var newstr = str.replace(/\bc[A-Za-z0-9]*/g, "auto");
The key thing to take from this is the use of the asterisk, also known as the wildcard operator. The asterisk tells the compiler to match one or more of the proceeding character(s).
- slide 3 of 4
Wildcard Operator and replace
var newstr = str.replace(/\b([A-Za-z]*)\.jpg/g, "picture.jpg");
var newstr = str.replace(/\W+/g, ' ');
- slide 4 of 4
The screenshot provided belongs to Steven Sheely and is for educational purposes only.