By JC Grubbs


2009-01-30 00:11:05 8 Comments

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?

18 comments

@Paul Jones 2018-10-18 18:37:43

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>

@CyberAP 2018-11-06 19:00:07

You're overwriting a closure variable, no need to use var here. Also, if you pass \b or \1 it would break.

@Ajit Hogade 2015-10-27 05:56:54

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.

@Ben Taliadoros 2017-10-27 14:26:48

Your replace_with variable will contain the DOM element not the value itself

@JBallin 2018-06-13 02:52:17

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.

@bobince 2009-02-01 03:43:49

"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.

@Mitar 2013-04-10 03:12:06

And have you measured that this is faster than regex?

@Krease 2013-04-24 18:41:42

This seems preferable, especially when needing to match on special regex characters like '.'

@user1985657 2013-06-12 22:47:12

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.

@bobince 2013-06-13 09:05:24

@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.

@Jugali Lakota 2017-01-12 11:18:15

Could someone have a basic benchmark of their respective performance?

@wdanda 2018-02-21 16:42:39

@Teekin 2018-08-18 16:16:36

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.

@Fernando Aguirre 2018-11-21 23:20:52

Excellent, fast and easy, thank you!

@Eric Wendelin 2009-01-30 00:15:40

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

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

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

"mystring".replace(re, "newstring");

@Jonathan Swinney 2010-11-09 23:04:27

If you need to use an expression like /\/word\:\w*$/, be sure to escape your backslashes: new RegExp( '\\/word\\:\\w*$' ).

@gravityboy 2011-06-20 21:02:53

wendelin If I have string and I want to replace all "10" with "a" how do I do that with your function?

@Eric Wendelin 2011-06-21 15:19:55

@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.

@CoolAJ86 2012-06-03 01:33:00

Full escape explanation: stackoverflow.com/a/6969486/151312

@dronus 2014-02-12 20:32:52

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...

@Goose 2015-06-05 18:44:26

An example of this passing a variable would make this a good answer. I'm still struggling after reading this.

@Hermann Ingjaldsson 2016-02-02 13:52:16

i always get 'regexp is not defined' error.

@oligofren 2016-02-15 15:23:20

@HermannIngjaldsson then you are writing it wrong. remember capitalization.

@fearis 2016-03-23 12:52:24

Honesty It doesnt work for me. Why not var re = new RegExp("(regex)("+yourVariable+")","g"); which will give you /(regex)(valueOfYourVariable)/g

@Dávid Horváth 2017-01-11 13:52:18

@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*$')

@Dante Cervantes 2018-04-16 22:21:07

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

@Kim Gentes 2018-06-02 00:33:24

This does answer the question. They want to variablize the search pattern.. and maybe even the replace pattern. This response has not done that.

@Wiktor Stribiżew 2018-11-12 16:50:03

@DanteCervantes A better answer is Gracenotes' as it has a full solution for cases when variable part can contain special regex metacharacters.

@zb226 2018-11-21 11:52:49

@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.

@Jonathan Swinney 2018-11-26 03:58:12

@zb226 I would sure like to edit it, but I can't edit a comment that is over 8 years old.

@user1511417 2018-12-20 15:47:33

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.

@Salman A 2014-09-14 19:55:19

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]"

@keen 2014-11-25 23:31:18

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 2015-08-26 15:53:22

why a downvote? coffeescript -IS- javascript with it's own specific syntax.

@Steven Penny 2012-11-28 15:32:33

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

var alpha = 'fig';
'food fight'.match(alpha + 'ht')[0]; // fight

@MetalGodwin 2013-08-20 12:35:29

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("]", ">"))

@Ry- 2013-08-16 19:53:34

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.

@Fareed Alnamrouti 2013-06-13 11:13:55

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>");

@Alex Li 2013-06-05 04:22:42

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.

@scripto 2013-05-08 10:30:36

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;
    };

@Gracenotes 2009-01-30 01:02:03

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".

@some 2009-01-30 10:31:05

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"));

@Gracenotes 2009-01-30 19:57:58

@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 2009-01-30 20:00:09

(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.

@chbrown 2012-12-15 21:12:50

developer.mozilla.org/en-US/docs/JavaScript/Guide/… offers a similar function, but they exclude -, and include =!:/.

@Lawrence Dol 2015-12-04 05:19:40

The correct term is "escape", not "quote". Just BTW.

@splintor 2016-11-14 20:48:23

Lodash has escapeRegExp for this - lodash.com/docs#escapeRegExp

@Novice 2018-02-11 20:08:25

Would /[^\w\s]/g be a safe alternative to /([.?*+^$[\]\\(){}|-])/g?

@tvanfosson 2009-01-30 00:16:39

this.replace( new RegExp( replaceThis, 'g' ), withThis );

@Wick 2019-04-04 15:20:13

I like this answer as it doesn't create the extra (& pointless) variable.

@unigogo 2009-02-01 09:14:23

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

@Jason S 2009-01-30 01:02:23

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)

@Jeremy Ruten 2009-01-30 00:19:19

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.

@vladkras 2013-07-09 04:16:21

yep, but in first example it uses pattern as variable, in 2nd as a string

Related Questions

Sponsored Content

53 Answered Questions

[SOLVED] How do I check if an element is hidden in jQuery?

79 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 5661071 View
  • 7034 Score
  • 79 Answer
  • Tags:   javascript arrays

3 Answered Questions

28 Answered Questions

50 Answered Questions

[SOLVED] How to replace all occurrences of a string in JavaScript

58 Answered Questions

[SOLVED] How do I redirect to another webpage?

71 Answered Questions

86 Answered Questions

[SOLVED] How do JavaScript closures work?

37 Answered Questions

[SOLVED] How do you get a timestamp in JavaScript?

17 Answered Questions

[SOLVED] How to decide when to use Node.js?

Sponsored Content