Skip to content
Fix Code Error

How do you use a variable in a regular expression?

March 13, 2021 by Code Error
Posted By: JC Grubbs

I would like to create a String.replaceAll() method in JavaScript and I’m thinking that using a regex would be most terse way to do it. However, I can’t figure out how to pass a variable in to a regex. I can do this already which will replace all the instances of "B" with "A".

"ABABAB".replace(/B/g, "A");

But I want to do something like this:

String.prototype.replaceAll = function(replaceThis, withThis) {
    this.replace(/replaceThis/g, withThis);
};

But obviously this will only replace the text "replaceThis"…so how do I pass this variable in to my regex string?

Solution

Instead of using the /regexd/g syntax, you can construct a new RegExp object:

var replace = "regex\d";
var re = new RegExp(replace,"g");

You can dynamically create regex objects this way. Then you will do:

"mystring1".replace(re, "newstring");
Answered By: Eric Wendelin

Related Articles

  • Reference - What does this regex mean?
  • How to "properly" create a custom object in JavaScript?
  • error LNK2005: ✘✘✘ already defined in…
  • How does JavaScript .prototype work?
  • How do I keep only the first map and when the game…
  • What is the 'new' keyword in JavaScript?
  • What does this symbol mean in JavaScript?
  • For-each over an array in JavaScript
  • How to format a phone number in a textfield
  • Next.js - Warning: Prop `dangerouslySetInnerHTML`…
  • How to filter a RecyclerView with a SearchView
  • shell script. how to extract string using regular…
  • What are the undocumented features and limitations…
  • Coffeescript class extend more bloat than Backbone extend
  • TypeScript metadata reflection references other…
  • insert tables in dataframe with years from 2000 to…
  • Pandas pivot_table: filter on aggregate function
  • Smart way to truncate long strings
  • Is there a regular expression to detect a valid…
  • Set the local state using useEffect on Redux prop change
  • explain backbone object and class creation pattern
  • How to use html template with vue.js
  • What is your most productive shortcut with Vim?
  • Is there some way to test my grammar which refer to…
  • RegEx match open tags except XHTML self-contained tags
  • Best way to replace multiple characters in a string?
  • Fix top buttons on scroll of list below
  • Best way to communicate between instances of the…
  • What's the difference between eval, exec, and compile?
  • How to find out what is referencing a detached DOM…
  • extending Backbone.Collection prototype
  • How to validate an email address using a regular expression?
  • Class vs. static method in JavaScript
  • Java replace all square brackets in a string
  • How can I parse a CSV string with JavaScript, which…
  • Get the name of an object's type
  • How can I pass a wct test while rearranging children…
  • JavaScript OOP in NodeJS: how?
  • String.replaceAll single backslashes with double backslashes
  • I want to solve the javascript OOP problems, but my…
  • How to use Regular Expressions (Regex) in Microsoft…
  • SQL find sum of entries by date including previous date
  • Ember build failing
  • Jest: TypeError: replaceAll is not a function
  • How does the "this" keyword work?
  • How to check if a string contains only digits in Java
  • Is it possible to apply CSS to half of a character?
  • How to remove special characters from a string?
  • How to use Servlets and Ajax?
  • can't use replaceAll or replace with nextjs/reactjs
  • What is the => assignment in C# in a property signature
  • How to replace all occurrences of a string in Javascript?
  • Inserting the succeeded word before 'and'…
  • Vue Cli 3 Local fonts not loading
  • Determine if string is in list in JavaScript
  • How do you parse and process HTML/XML in PHP?
  • Filtering an object based on key, then constructing…
  • I need to sum values with specific condition
  • Swift extract regex matches
  • Regex Named Groups in Java
  • Forward slash in Java Regex
  • Regular expression to check if password is "8…
  • Use of String.Format in JavaScript?
  • How do I rotate text in css?
  • How to replace matches via regex with an array of strings?
  • Regular expression for floating point numbers
  • Bring element to front using CSS
  • How to do a regular expression replace in MySQL?
  • How can I perform a str_replace in JavaScript,…
  • Reactjs - SyntaxError: Octal literals are not…
  • How do I create a custom Error in JavaScript?
  • What is difference between Lightsail and EC2?
  • Regular expression to match numbers with or without…
  • Usage of __slots__?
  • How to Watch Object Property within a Vue Plugin
  • How do I correctly clone a JavaScript object?
  • Obtain most recent value for based on index in a…
  • Cannot make table responsive
  • The definitive guide to form-based website authentication
  • How to grep (search) committed code in the Git history
  • Regular expression for only characters a-z, A-Z
  • Difference between `constexpr` and `const`
  • Are 'Arrow Functions' and 'Functions' equivalent /…
  • "Uncaught TypeError: undefined is not a function" -…
  • Regex to match only uppercase "words" with some exceptions
  • How can I show the caption of a single grid item…
  • Active tab issue on page load HTML
  • Regex matching in a Bash if statement
  • Remove ALL white spaces from text
  • Java regular expression OR operator
  • Regular expressions in C: examples?
  • NullpointerException error while working with…
  • Add calculated column to df2 for every row entry in…
  • How can I close an element when the div content or a…
  • Execute an expression rather than calling a method…
  • Why does backbone use the _.extend() method throughout?
  • Python string.replace regular expression
  • Design DFA accepting binary strings divisible by a…
  • What are the nuances of scope prototypal /…
  • attributeChanged not getting fired on 2 way data…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How do I erase an element from std::vector by index?

Next Post:

How to change max_allowed_packet size

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error