1567

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?

daaawx
  • 2,268
  • 2
  • 12
  • 13
JC Grubbs
  • 34,411
  • 27
  • 64
  • 74
  • 12
    Note that we're currently [working on adding this functionality to JavaScript](https://github.com/benjamingr/RegExp.escape) if you have an opinion about it please join the discussion. – Benjamin Gruenbaum Jun 23 '15 at 11:38

23 Answers23

2077

Instead of using the /regex\d/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");
Eric Wendelin
  • 39,122
  • 8
  • 59
  • 87
  • 303
    If you need to use an expression like `/\/word\:\w*$/`, be sure to escape your backslashes: `new RegExp( '\\/word\\:\\w*$' )`. – Jonathan Swinney Nov 09 '10 at 23:04
  • 1
    wendelin If I have string and I want to replace all "10" with "a" how do I do that with your function? – gravityboy Jun 20 '11 at 21:02
  • 2
    @gravityboy You can do ('' + myNumber).replace(/10/g, 'a') or if you want hex numbers, you can do parseInt('' + myNumber, 16) to convert to hex from decimal. – Eric Wendelin Jun 21 '11 at 15:19
  • 42
    The question suggests that the RegEx is only used to do a constant string replacement. So this is answer is wrong as it would fail if the string contains RegEx meta characters. Sad it is voted this high, will make many headaches... – dronus Feb 12 '14 at 20:32
  • 24
    An example of this passing a variable would make this a good answer. I'm still struggling after reading this. – Goose Jun 05 '15 at 18:44
  • 1
    @HermannIngjaldsson then you are writing it wrong. remember capitalization. – oligofren Feb 15 '16 at 15:23
  • Honesty It doesnt work for me. Why not var re = new RegExp("(regex)("+yourVariable+")","g"); which will give you /(regex)(valueOfYourVariable)/g – fearis Mar 23 '16 at 12:52
  • 3
    @JonathanSwinney: `/` has no special meaning if you construct regex from string, so you don't need to escape it. `/\/word\:\w*$/` should be `new RegExp('/word\\:\\w*$')` – Dávid Horváth Jan 11 '17 at 13:52
  • this is not working for me, im doing this ``` var reg = "$times" var regexp = new RegExp(reg,"g") var replaceFor = times console.log(reg,replaceFor,'here'); var _newTpl = _tpl.replace(regexp, replaceFor)``` and is not working – Dante Cervantes Apr 16 '18 at 22:21
  • This does answer the question. They want to variablize the search pattern.. and maybe even the replace pattern. This response has not done that. – Kim Gentes Jun 02 '18 at 00:33
  • @DanteCervantes A better answer is [Gracenotes'](https://stackoverflow.com/a/494122/3832970) as it has a full solution for cases when variable part can contain special regex metacharacters. – Wiktor Stribiżew Nov 12 '18 at 16:50
  • @JonathanSwinney: As you've already acknowledged that it contains wrong information, consider *at least editing* your first comment! Yes, RegExp meta characters also need to be escaped in the string version, but the forward slash `/` is no such meta character and btw, neither is the colon `:`. As it stands this answer and comments will lead to confusion. – zb226 Nov 21 '18 at 11:52
  • @zb226 I would sure like to edit it, but I can't edit a comment that is over 8 years old. – Jonathan Swinney Nov 26 '18 at 03:58
  • This answer is not useful. How do you use a variable in a regex? What if you want to do something like this: `\bSTRING\b` where STRING is a variable. – user1511417 Dec 20 '18 at 15:47
  • Honestly I'm having trouble understanding how to actually use this. What is "replace"? What is "re"? The naming is a bit confusing. – devamat Jan 07 '20 at 04:25
  • If you get an invalid regex error, make sure to double your slashes '\\' –  Mar 11 '20 at 20:01
  • tanks :) this is great – hassan khademi Aug 11 '20 at 10:36
  • 1
    The examples in this answer are not as clear as the could be due to the "collision" between the `replace` variable and the `replace` function. I'd suggest using `s` instead of `replace` for the variable name. – rinogo Dec 17 '20 at 23:47
  • @dronus In current Chrome, I am testing it and it works same, with and also without escaped all special characters. It needs only escaped backslash (= double backslash). I tried the escapeRegExp function from MDN site, but I realized that if a string is not written literaly, like created by escapeAllSpecialChars function, then backslashes remain in that and are passed on and then it doesn’t work. – Starboy Jan 28 '21 at 13:51
  • How would this accepted solution need to be modified so that it would work if the variable contains an asterisk (*)? – Michael Swarts Mar 02 '21 at 18:29
230

As Eric Wendelin mentioned, you can do something like this:

str1 = "pattern"
var re = new RegExp(str1, "g");
"pattern matching .".replace(re, "regex");

This yields "regex matching .". However, it will fail if str1 is ".". You'd expect the result to be "pattern matching regex", replacing the period with "regex", but it'll turn out to be...

regexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregex

This is because, although "." is a String, in the RegExp constructor it's still interpreted as a regular expression, meaning any non-line-break character, meaning every character in the string. For this purpose, the following function may be useful:

 RegExp.quote = function(str) {
     return str.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
 };

Then you can do:

str1 = "."
var re = new RegExp(RegExp.quote(str1), "g");
"pattern matching .".replace(re, "regex");

yielding "pattern matching regex".

Qtax
  • 31,392
  • 7
  • 73
  • 111
Gracenotes
  • 2,484
  • 1
  • 13
  • 8
  • 4
    You know that the first parameter to replace can be a normal string and don't have to be a regexp? str1 = "."; alert("pattern matching .".replace(str1, "string")); – some Jan 30 '09 at 10:31
  • @some: of course. That's because the above example is trivial. When you need to search for or replace a pattern combined with a regular string, do str.match(new RegExp("https?://" + RegExp.escape(myDomainName)), for instance. It's annoying that the escape function is not built in. – Gracenotes Jan 30 '09 at 19:57
  • (continued) Plus, apparentl JC Grubbs required a global replace; implementing a global replace with String.replace(String, String) could be slow for large input. I'm just saying, the top two solutions are buggy, and will fail unexpected on certain input. – Gracenotes Jan 30 '09 at 20:00
  • 5
    https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions offers a similar function, but they exclude `-`, and include `=!:/`. – chbrown Dec 15 '12 at 21:12
  • 8
    The correct term is "escape", not "quote". Just BTW. – Lawrence Dol Dec 04 '15 at 05:19
  • Lodash has escapeRegExp for this - https://lodash.com/docs#escapeRegExp – splintor Nov 14 '16 at 20:48
  • Would `/[^\w\s]/g` be a safe alternative to `/([.?*+^$[\]\\(){}|-])/g`? – Novice Feb 11 '18 at 20:08
  • @LawrenceDol Actually, both are acceptable. Bash and Lisp programmers often talk about quoting expressions, while most string manipulation code talks about escape sequences. Backslash quotes or escapes the following character, enabling literal or special treatment – D. Ben Knoble Apr 30 '19 at 21:06
  • I want to use a loop, but it does nothing: `for (reg of regs) { var re = new RegExp(reg, "g");bodyPost.replace(re, '') }` – Timo Jan 17 '21 at 11:24
  • Indeed, why do you [escape `-`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#escaping)?.. – x-yuri Apr 01 '21 at 02:58
124

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

As always: don't use regex unless you have to. For a simple string replace, the idiom is:

'ABABAB'.split('B').join('A')

Then you don't have to worry about the quoting issues mentioned in Gracenotes's answer.

Liam
  • 22,818
  • 25
  • 93
  • 157
bobince
  • 498,320
  • 101
  • 621
  • 807
  • 12
    And have you measured that this is faster than regex? – Mitar Apr 10 '13 at 03:12
  • 3
    This seems preferable, especially when needing to match on special regex characters like '.' – Krease Apr 24 '13 at 18:41
  • 1
    Uhm... Doesn't split take a RegExp too; if so, wouldn't it cause the same problem ? Anyway... .split().join() may be slower on some platforms, because it's two operations, whereas .replace() is one operation and may be optimized. –  Jun 12 '13 at 22:47
  • 5
    @PacMan--: both `split` and `replace` can take either a string or a `RegExp` object. The problem that `replace` has that `split` doesn't is that when you use a string you only get a single replacement. – bobince Jun 13 '13 at 09:05
  • Could someone have a basic benchmark of their respective performance? – Jugali Lakota Jan 12 '17 at 11:18
  • 2
    benchmark here: https://jsperf.com/replace-vs-split-join-vs-replaceall/23 – Wagner Danda da Silva Filho Feb 21 '18 at 16:42
  • It's an okay point of view, but the question is explicitly about how to use variable names in regex, not about what you can use instead of regex. – Teekin Aug 18 '18 at 16:16
  • 1
    @wagnerdasilva Micro-optimizations are relevant if you're writing a library or processing thousands of strings synchronously/in loops, otherwise they have no discernable benefit https://blog.codinghorror.com/the-sad-tragedy-of-micro-optimization-theater/ – Drenai Aug 21 '19 at 06:40
  • "otherwise they have no discernible benefit" You don't consider making your code damn-near unreadable to be a benefit? – floodlitworld Jan 30 '21 at 17:18
60

If you want to get ALL occurrences (g), be case insensitive (i), and use boundaries so that it isn't a word within another word (\\b):

re = new RegExp(`\\b${replaceThis}\\b`, 'gi');

Example:

let inputString = "I'm John, or johnny, but I prefer john.";
let replaceThis = "John";
let re = new RegExp(`\\b${replaceThis}\\b`, 'gi');
console.log(inputString.replace(re, "Jack")); // I'm Jack, or johnny, but I prefer Jack.
JBallin
  • 4,767
  • 33
  • 38
  • 1
    thank you! (afaict, yours is the only answer explicitly with Emacs/`rx`-style interpolation, via template strings.) – sam boosalis Apr 08 '20 at 03:30
36

For anyone looking to use variable with the match method, this worked for me

var alpha = 'fig';
'food fight'.match(alpha + 'ht')[0]; // fight
Steven Penny
  • 82,115
  • 47
  • 308
  • 348
34

This:

var txt=new RegExp(pattern,attributes);

is equivalent to this:

var txt=/pattern/attributes;

See http://www.w3schools.com/jsref/jsref_obj_regexp.asp.

Paige Ruten
  • 157,734
  • 36
  • 172
  • 191
29
this.replace( new RegExp( replaceThis, 'g' ), withThis );
Mike Samuel
  • 109,453
  • 27
  • 204
  • 234
tvanfosson
  • 490,224
  • 93
  • 683
  • 780
16

You want to build the regular expression dynamically and for this the proper solutuion is to use the new RegExp(string) constructor. In order for constructor to treat special characters literally, you must escape them. There is a built-in function in jQuery UI autocomplete widget called $.ui.autocomplete.escapeRegex:

[...] you can make use of the built-in $.ui.autocomplete.escapeRegex function. It'll take a single string argument and escape all regex characters, making the result safe to pass to new RegExp().

If you are using jQuery UI you can use that function, or copy its definition from the source:

function escapeRegex( value ) {
    return value.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" );
}

And use it like this:

"[z-a][z-a][z-a]".replace(new RegExp(escapeRegex("[z-a]"), "g"), "[a-z]");
//            escapeRegex("[z-a]")       -> "\[z\-a\]"
// new RegExp(escapeRegex("[z-a]"), "g") -> /\[z\-a\]/g
// end result                            -> "[a-z][a-z][a-z]"
Salman A
  • 229,425
  • 77
  • 398
  • 489
10
String.prototype.replaceAll = function (replaceThis, withThis) {
   var re = new RegExp(replaceThis,"g"); 
   return this.replace(re, withThis);
};
var aa = "abab54..aba".replaceAll("\\.", "v");

Test with this tool

unigogo
  • 537
  • 4
  • 9
6
String.prototype.replaceAll = function(a, b) {
    return this.replace(new RegExp(a.replace(/([.?*+^$[\]\\(){}|-])/ig, "\\$1"), 'ig'), b)
}

Test it like:

var whatever = 'Some [b]random[/b] text in a [b]sentence.[/b]'

console.log(whatever.replaceAll("[", "<").replaceAll("]", ">"))
MetalGodwin
  • 3,453
  • 2
  • 12
  • 10
5

To satisfy my need to insert a variable/alias/function into a Regular Expression, this is what I came up with:

oldre = /xx\(""\)/;
function newre(e){
    return RegExp(e.toString().replace(/\//g,"").replace(/xx/g, yy), "g")
};

String.prototype.replaceAll = this.replace(newre(oldre), "withThis");

where 'oldre' is the original regexp that I want to insert a variable, 'xx' is the placeholder for that variable/alias/function, and 'yy' is the actual variable name, alias, or function.

Alex Li
  • 51
  • 1
  • 2
  • After trying every single solution for inserting a variable inside the regular expression, yours was the only one that worked for me. Thank you sooo much! – RoberRM Jun 26 '20 at 01:23
5

And the coffeescript version of Steven Penny's answer, since this is #2 google result....even if coffee is just javascript with a lot of characters removed...;)

baz = "foo"
filter = new RegExp(baz + "d")
"food fight".match(filter)[0] // food

and in my particular case

robot.name=hubot
filter = new RegExp(robot.name)
if msg.match.input.match(filter)
  console.log "True!"
keen
  • 756
  • 9
  • 10
4

Here's another replaceAll implementation:

    String.prototype.replaceAll = function (stringToFind, stringToReplace) {
        if ( stringToFind == stringToReplace) return this;
        var temp = this;
        var index = temp.indexOf(stringToFind);
        while (index != -1) {
            temp = temp.replace(stringToFind, stringToReplace);
            index = temp.indexOf(stringToFind);
        }
        return temp;
    };
scripto
  • 2,246
  • 1
  • 12
  • 13
3

You can use this if $1 not work with you

var pattern = new RegExp("amman","i");
"abc Amman efg".replace(pattern,"<b>"+"abc Amman efg".match(pattern)[0]+"</b>");
Fareed Alnamrouti
  • 26,439
  • 4
  • 77
  • 71
3

While you can make dynamically-created RegExp's (as per the other responses to this question), I'll echo my comment from a similar post: The functional form of String.replace() is extremely useful and in many cases reduces the need for dynamically-created RegExp objects. (which are kind of a pain 'cause you have to express the input to the RegExp constructor as a string rather than use the slashes /[A-Z]+/ regexp literal format)

Community
  • 1
  • 1
Jason S
  • 171,795
  • 155
  • 551
  • 900
3

This self calling function will iterate over replacerItems using an index, and change replacerItems[index] globally on the string with each pass.

  const replacerItems = ["a", "b", "c"];    

    function replacer(str, index){
          const item = replacerItems[index];
          const regex = new RegExp(`[${item}]`, "g");
          const newStr = str.replace(regex, "z");
          if (index < replacerItems.length - 1) {
            return replacer(newStr, index + 1);
          }
          return newStr;
    }

// console.log(replacer('abcdefg', 0)) will output 'zzzdefg'
2

You can always use indexOf repeatedly:

String.prototype.replaceAll = function(substring, replacement) {
    var result = '';
    var lastIndex = 0;

    while(true) {
        var index = this.indexOf(substring, lastIndex);
        if(index === -1) break;
        result += this.substring(lastIndex, index) + replacement;
        lastIndex = index + substring.length;
    }

    return result + this.substring(lastIndex);
};

This doesn’t go into an infinite loop when the replacement contains the match.

Ry-
  • 199,309
  • 51
  • 404
  • 420
1

Your solution is here:

Pass a variable to regular expression.

The one which I have implemented is by taking the value from a text field which is the one you want to replace and another is the "replace with" text field, getting the value from text-field in a variable and setting the variable to RegExp function to further replace. In my case I am using Jquery, you also can do it by only JavaScript too.

JavaScript code:

  var replace =document.getElementById("replace}"); // getting a value from a text field with I want to replace
  var replace_with = document.getElementById("with"); //Getting the value from another text fields with which I want to replace another string.

  var sRegExInput = new RegExp(replace, "g");    
  $("body").children().each(function() {
    $(this).html($(this).html().replace(sRegExInput,replace_with));
  });

This code is on Onclick event of a button, you can put this in a function to call.

So now You can pass variable in replace function.

Saikat
  • 8,190
  • 12
  • 69
  • 94
Ajit Hogade
  • 984
  • 7
  • 25
1

None of these answers were clear to me. I eventually found a good explanation at http://burnignorance.com/php-programming-tips/how-to-use-a-variable-in-replace-function-of-javascript/

The simple answer is:

var search_term = new RegExp(search_term, "g");    
text = text.replace(search_term, replace_term);

For example:

$("button").click(function() {
  Find_and_replace("Lorem", "Chocolate");
  Find_and_replace("ipsum", "ice-cream");
});

function Find_and_replace(search_term, replace_term) {
  text = $("textbox").html();
  var search_term = new RegExp(search_term, "g");
  text = text.replace(search_term, replace_term);
  $("textbox").html(text);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textbox>
  Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum
</textbox>
<button>Click me</button>
Paul Chris Jones
  • 1,491
  • 17
  • 18
  • 1
    You're overwriting a closure variable, no need to use `var` here. Also, if you pass `\b` or `\1` it would break. – CyberAP Nov 06 '18 at 19:00
0

For multiple replace without regular expressions I went with the following:

      let str = "I am a cat man. I like cats";
      let find = "cat";
      let replace = "dog";


      // Count how many occurrences there are of the string to find 
      // inside the str to be examined.
      let findCount = str.split(find).length - 1;

      let loopCount = 0;

      while (loopCount < findCount) 
      {
        str = str.replace(find, replace);
        loopCount = loopCount + 1;
      }  

      console.log(str);
      // I am a dog man. I like dogs

The important part of the solution was found here

0

As a relative JavaScript novice, the accepted answer https://stackoverflow.com/a/494046/1904943 is noted / appreciated, but it is not very intuitive.

Here is a simpler interpretation, by example (using a simple JavaScript IDE).

myString = 'apple pie, banana loaf';

console.log(myString.replaceAll(/pie/gi, 'PIE'))
// apple PIE, banana loaf

console.log(myString.replaceAll(/\bpie\b/gi, 'PIE'))
// apple PIE, banana loaf

console.log(myString.replaceAll(/pi/gi, 'PIE'))
// apple PIEe, banana loaf

console.log(myString.replaceAll(/\bpi\b/gi, 'PIE'))
// [NO EFFECT] apple pie, banana loaf

const match_word = 'pie';

console.log(myString.replaceAll(/match_word/gi, '**PIE**'))
// [NO EFFECT] apple pie, banana loaf

console.log(myString.replaceAll(/\b`${bmatch_word}`\b/gi, '**PIE**'))
// [NO EFFECT] apple pie, banana loaf

// ----------------------------------------
// ... new RegExp(): be sure to \-escape your backslashes: \b >> \\b ...

const match_term = 'pie';
const match_re = new RegExp(`(\\b${match_term}\\b)`, 'gi')

console.log(myString.replaceAll(match_re, 'PiE'))
// apple PiE, banana loaf

console.log(myString.replace(match_re, '**PIE**'))
// apple **PIE**, banana loaf

console.log(myString.replaceAll(match_re, '**PIE**'))
// apple **PIE**, banana loaf

Application

E.g.: replacing (color highlighting) words in string / sentence, [optionally] if the search term matches a more than a user-defined proportion of the matched word.

Note: original character case of matched term is retained. hl: highlight; re: regex | regular expression

mySentence = "Apple, boOk? BOoks; booKEd. BookMark, 'BookmarkeD', bOOkmarks! bookmakinG, Banana; bE, BeEn, beFore."

function replacer(mySentence, hl_term, hl_re) {
    console.log('mySentence [raw]:', mySentence)
    console.log('hl_term:', hl_term, '| hl_term.length:', hl_term.length)
    cutoff = hl_term.length;
    console.log('cutoff:', cutoff)

    // `.match()` conveniently collects multiple matched items
    // (including partial matches) into an [array]
    const hl_terms  = mySentence.toLowerCase().match(hl_re, hl_term);
    if (hl_terms == null) {
        console.log('No matches to hl_term "' + hl_term + '"; echoing input string then exiting ...')
        return mySentence;
    }
    console.log('hl_terms:', hl_terms)
    for (let i = 0;  i < hl_terms.length; i++) {
        console.log('----------------------------------------')
        console.log('[' + i + ']:', hl_terms[i], '| length:', hl_terms[i].length, '| parseInt(0.7(length)):', parseInt(0.7*hl_terms[i].length))
        // TEST: if (hl_terms[i].length >= cutoff*10) {
        if (cutoff >= parseInt(0.7 * hl_terms[i].length)) {
            var match_term = hl_terms[i].toString();

            console.log('matched term:', match_term, '[cutoff length:', cutoff, '| 0.7(matched term length):', parseInt(0.7 * hl_terms[i].length))

            const match_re = new RegExp(`(\\b${match_term}\\b)`, 'gi')

            mySentence = mySentence.replaceAll(match_re, '<font style="background:#ffe74e">$1</font>');
        }
        else {
            var match_term = hl_terms[i].toString();
            console.log('NO match:', match_term, '[cutoff length:', cutoff, '| 0.7(matched term length):', parseInt(0.7 * hl_terms[i].length))
        }
    }
    return mySentence;
}

// TESTS:
// const hl_term = 'be';
// const hl_term = 'bee';
// const hl_term = 'before';
// const hl_term = 'book';
const hl_term = 'bookma';
// const hl_term = 'Leibniz';

// This regex matches from start of word:
const hl_re = new RegExp(`(\\b${hl_term}[A-z]*)\\b`, 'gi')

mySentence = replacer(mySentence, hl_term, hl_re);
console.log('mySentence [processed]:', mySentence)

Output

mySentence [raw]: Apple, boOk? BOoks; booKEd. BookMark, 'BookmarkeD',
bOOkmarks! bookmakinG, Banana; bE, BeEn, beFore.

hl_term: bookma | hl_term.length: 6
cutoff: 6
hl_terms: Array(4) [ "bookmark", "bookmarked", "bookmarks", "bookmaking" ]

----------------------------------------
[0]: bookmark | length: 8 | parseInt(0.7(length)): 5
matched term: bookmark [cutoff length: 6 | 0.7(matched term length): 5
----------------------------------------
[1]: bookmarked | length: 10 | parseInt(0.7(length)): 7
NO match: bookmarked [cutoff length: 6 | 0.7(matched term length): 7
----------------------------------------
[2]: bookmarks | length: 9 | parseInt(0.7(length)): 6
matched term: bookmarks [cutoff length: 6 | 0.7(matched term length): 6
----------------------------------------
[3]: bookmaking | length: 10 | parseInt(0.7(length)): 7
NO match: bookmaking [cutoff length: 6 | 0.7(matched term length): 7

mySentence [processed]: Apple, boOk? BOoks; booKEd.
<font style="background:#ffe74e">BookMark</font>, 'BookmarkeD',
<font style="background:#ffe74e">bOOkmarks</font>! bookmakinG,
Banana; bE, BeEn, beFore.
Victoria Stuart
  • 3,146
  • 2
  • 28
  • 26
0

If you pass the variable with the correct syntax you can do this like so with the code below.

This has the added benefit of using the flags in the same variable.

Also you don't have to double escape \ in the regexp when it comes to \w etc.

var str = 'regexVariable example: This is my example of RegExp replacing with a regexVariable.'
var reVar = /(.*?)(regex\w+?iable)(.+?)/gi;
var resStr = str.replace(new RegExp(reVar), '$1 :) :) :) $2 :) :) :)$3');
console.log(resStr);

// Returns:
// :) :) :) regexVariable :) :) :) example: This is my example of RegExp replacing with a  :) :) :) regexVariable :) :) :).

prototype version as per the OPs example:

var str = 'regexVariable prototype: This is my example of RegExp replacing with a regexVariable.'

String.prototype.regexVariable = function(reFind, reReplace) {
return str.replace(new RegExp(reFind), reReplace);
}

var reVar = /(.*?)(regex\w+?iable)(.+?)/gi;

console.log(str.regexVariable(reVar, '$1 :) :) :) $2 :) :) :)$3'));

// Returns:
// :) :) :) regexVariable :) :) :) prototype: This is my example of replacing with a  :) :) :) regexVariable :) :) :).
Ste
  • 752
  • 1
  • 5
  • 18
0

You can use a string as a regex, dont forget to use new RegExp

example:

var yourFunction = new RegExp(
        '^-?\\d+(?:\\.\\d{0,' + yourVar + '})?'
      )
x-rw
  • 1,253
  • 10
  • 24