Regular Expressions in JavaScript

Our first program demonstrates the use of regular expressions in JavaScript. Here’s the full source code with explanations:

// In JavaScript, we use the built-in RegExp object for regular expressions

// This tests whether a pattern matches a string.
let match = /p([a-z]+)ch/.test("peach");
console.log(match);

// We can create a RegExp object for more complex operations
let r = new RegExp("p([a-z]+)ch");

// Here's a match test like we saw earlier
console.log(r.test("peach"));

// This finds the match for the regexp
console.log("peach punch".match(r)[0]);

// This also finds the first match but returns the
// start and end indexes for the match instead of the
// matching text.
let result = "peach punch".match(r);
console.log("idx:", [result.index, result.index + result[0].length]);

// The match method includes information about
// both the whole-pattern matches and the submatches
// within those matches.
console.log("peach punch".match(r));

// To find all matches for a regexp, we use the global flag 'g'
r = new RegExp("p([a-z]+)ch", "g");
console.log("peach punch pinch".match(r));

// Providing a limit to the number of matches
console.log("peach punch pinch".match(r).slice(0, 2));

// The replace method can be used to replace subsets of strings with other values
console.log("a peach".replace(r, "<fruit>"));

// We can also use a function to transform matched text
console.log("a peach".replace(r, (match) => match.toUpperCase()));

To run the program, save it as regular-expressions.js and use node:

$ node regular-expressions.js
true
true
peach
idx: [ 0, 5 ]
[ 'peach', 'ea', index: 0, input: 'peach punch', groups: undefined ]
[ 'peach', 'punch', 'pinch' ]
[ 'peach', 'punch' ]
a <fruit>
a PEACH

JavaScript’s regular expression syntax is similar to many other programming languages. It provides methods like test(), match(), and replace() for working with regular expressions.

The RegExp object in JavaScript is equivalent to the regexp.Regexp struct in Go. While Go has separate methods for different operations (like FindString, FindStringSubmatch, etc.), JavaScript typically uses the match() method with different flags to achieve similar results.

JavaScript doesn’t have a direct equivalent to Go’s MustCompile. In JavaScript, invalid regular expressions will throw an error when the RegExp object is created or when the regex literal is evaluated.

For a complete reference on JavaScript regular expressions, check the MDN Regular Expressions Guide.