My Journey to Learning Javascript: Notes- Regular Expressions



Regular expressions are created starting and ending with a forward slash (/) marking the beginning and end, as follows:

var myRegEx = /paul/;


You use the .replace() method to replace a substring like this:


var myString = “ Paul, Paula, Pauline, paul, Paul”;
var myString = myString.replace(myRegExp, “Ringo”);
This returns “Ringo, Paula, Pauline, paul, Paul”
*This will replace only the first occurence of paul. This is a common behavior of RegEx objects. Once the first occurrence is found then it stops.



There are three attributes to better define RegEx. There is (G) a global match that looks for all the patterns. (I) for case sensitivity meaning paul and Paul would be the same. And (M) Multi-line flag. This specifies that the special characters ^ and $ can match the beginning and the end of lines as well as the beginning and end of the string.

For example using (G):

var myRegExp = /Paul/gi;
var myString = “ Paul, Paula, Pauline, paul, Paul”;
var myString = myString.replace(myRegExp, “Ringo”);
Returns: “Ringo, Ringola, Ringoline, Ringo, Ringo”


To replace only a single word instead of that pattern thats also a part of another word, you would need to use special characters.