From 3710647f46798dbc1a2c14ba63a95d3b0f8f6bf7 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Mon, 10 Aug 2020 11:59:43 -0500 Subject: [PATCH] Add Interpolate A String Into A Regex as a javascript til --- README.md | 3 +- .../interpolate-a-string-into-a-regex.md | 31 +++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 javascript/interpolate-a-string-into-a-regex.md diff --git a/README.md b/README.md index f6a745f..65c39e2 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ and pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). -_944 TILs and counting..._ +_945 TILs and counting..._ --- @@ -333,6 +333,7 @@ _944 TILs and counting..._ - [Immutable Remove With The Spread Operator](javascript/immutable-remove-with-the-spread-operator.md) - [Initialize A New JavaScript Project With Yarn](javascript/initialize-a-new-javascript-project-with-yarn.md) - [Install The Latest Version Of Node With Nvm](javascript/install-the-latest-version-of-node-with-nvm.md) +- [Interpolate A String Into A Regex](javascript/interpolate-a-string-into-a-regex.md) - [ISO-8601 Formatted Dates Are Interpreted As UTC](javascript/iso-8601-formatted-dates-are-interpreted-as-utc.md) - [Link A JavaScript Package Locally](javascript/link-a-javascript-package-locally.md) - [List Top-Level NPM Dependencies](javascript/list-top-level-npm-dependencies.md) diff --git a/javascript/interpolate-a-string-into-a-regex.md b/javascript/interpolate-a-string-into-a-regex.md new file mode 100644 index 0000000..9114f3a --- /dev/null +++ b/javascript/interpolate-a-string-into-a-regex.md @@ -0,0 +1,31 @@ +# Interpolate A String Into A Regex + +You can build up strings with concatenation or the template literal syntax. If +you're incorporating variables as part of this string building, that's called +interpolation. + +But what if you need to interpolate variables into a regular expression +(regex)? + +A regex literal looks like this: + +```javascript +const myRegex = /^Some Customizable Text$/; +``` + +This works great for fixed strings, but won't cut it if you need to work +_variable_ strings. + +What's needed to work with variables is the +[`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) +constructor: + +```javascript +const customizableString = "Some Customizable Text"; +const myRegex = new RegExp(`^${customizableString}$`); +``` + +You can build up some string with string variables and regex syntax and `new +RegExp()` will turn it into a regex. + +[source](https://makandracards.com/makandra/15879-javascript-how-to-generate-a-regular-expression-from-a-string)