How do you use a variable in a regular expression?
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?
javascript regex
add a comment |
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?
javascript regex
3
Note that we're currently working on adding this functionality to JavaScript if you have an opinion about it please join the discussion.
– Benjamin Gruenbaum
Jun 23 '15 at 11:38
add a comment |
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?
javascript regex
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?
javascript regex
javascript regex
edited Dec 5 '16 at 3:05
user663031
asked Jan 30 '09 at 0:11
JC GrubbsJC Grubbs
14k266172
14k266172
3
Note that we're currently working on adding this functionality to JavaScript if you have an opinion about it please join the discussion.
– Benjamin Gruenbaum
Jun 23 '15 at 11:38
add a comment |
3
Note that we're currently working on adding this functionality to JavaScript if you have an opinion about it please join the discussion.
– Benjamin Gruenbaum
Jun 23 '15 at 11:38
3
3
Note that we're currently working on adding this functionality to JavaScript if you have an opinion about it please join the discussion.
– Benjamin Gruenbaum
Jun 23 '15 at 11:38
Note that we're currently working on adding this functionality to JavaScript if you have an opinion about it please join the discussion.
– Benjamin Gruenbaum
Jun 23 '15 at 11:38
add a comment |
18 Answers
18
active
oldest
votes
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");
228
If you need to use an expression like//word:w*$/, be sure to escape your backslashes:new RegExp( '\/word\:\w*$' ).
– Jonathan Swinney
Nov 9 '10 at 23:04
6
Full escape explanation: stackoverflow.com/a/6969486/151312
– CoolAJ86
Jun 3 '12 at 1:33
18
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
10
An example of this passing a variable would make this a good answer. I'm still struggling after reading this.
– Goose
Jun 5 '15 at 18:44
3
@JonathanSwinney:/has no special meaning if you construct regex from string, so you don't need to escape it.//word:w*$/should benew RegExp('/word\:\w*$')
– Dávid Horváth
Jan 11 '17 at 13:52
|
show 12 more comments
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".
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
4
developer.mozilla.org/en-US/docs/JavaScript/Guide/… offers a similar function, but they exclude-, and include=!:/.
– chbrown
Dec 15 '12 at 21:12
4
The correct term is "escape", not "quote". Just BTW.
– Lawrence Dol
Dec 4 '15 at 5:19
|
show 2 more comments
"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.
9
And have you measured that this is faster than regex?
– Mitar
Apr 10 '13 at 3:12
2
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.
– user1985657
Jun 12 '13 at 22:47
5
@PacMan--: bothsplitandreplacecan take either a string or aRegExpobject. The problem thatreplacehas thatsplitdoesn't is that when you use a string you only get a single replacement.
– bobince
Jun 13 '13 at 9:05
1
benchmark here: jsperf.com/replace-vs-split-join-vs-replaceall/23
– wdanda
Feb 21 '18 at 16:42
|
show 3 more comments
For anyone looking to use variable with the match method, this worked for me
var alpha = 'fig';
'food fight'.match(alpha + 'ht')[0]; // fight
Thanks, you help me lot
– kumaresan_sd
Jan 28 at 10:07
add a comment |
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.
15
yep, but in first example it usespatternas variable, in 2nd as a string
– vladkras
Jul 9 '13 at 4:16
1
I actually find this to be the clearest answer.
– Teekin
Aug 18 '18 at 16:17
add a comment |
this.replace( new RegExp( replaceThis, 'g' ), withThis );
add a comment |
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.
add a comment |
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
add a comment |
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.escapeRegexfunction. It'll take a single string
argument and escape all regex characters, making the result safe to
pass tonew 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]"
add a comment |
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;
};
add a comment |
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("]", ">"))
add a comment |
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)
add a comment |
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.
add a comment |
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!"
why a downvote? coffeescript -IS- javascript with it's own specific syntax.
– keen
Aug 26 '15 at 15:53
add a comment |
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>");
add a comment |
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.
add a comment |
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.
Your replace_with variable will contain the DOM element not the value itself
– Ben Taliadoros
Oct 27 '17 at 14:26
add a comment |
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>
You're overwriting a closure variable, no need to usevarhere. Also, if you passbor1it would break.
– CyberAP
Nov 6 '18 at 19:00
add a comment |
protected by Community♦ Sep 19 '18 at 9:52
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
18 Answers
18
active
oldest
votes
18 Answers
18
active
oldest
votes
active
oldest
votes
active
oldest
votes
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");
228
If you need to use an expression like//word:w*$/, be sure to escape your backslashes:new RegExp( '\/word\:\w*$' ).
– Jonathan Swinney
Nov 9 '10 at 23:04
6
Full escape explanation: stackoverflow.com/a/6969486/151312
– CoolAJ86
Jun 3 '12 at 1:33
18
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
10
An example of this passing a variable would make this a good answer. I'm still struggling after reading this.
– Goose
Jun 5 '15 at 18:44
3
@JonathanSwinney:/has no special meaning if you construct regex from string, so you don't need to escape it.//word:w*$/should benew RegExp('/word\:\w*$')
– Dávid Horváth
Jan 11 '17 at 13:52
|
show 12 more comments
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");
228
If you need to use an expression like//word:w*$/, be sure to escape your backslashes:new RegExp( '\/word\:\w*$' ).
– Jonathan Swinney
Nov 9 '10 at 23:04
6
Full escape explanation: stackoverflow.com/a/6969486/151312
– CoolAJ86
Jun 3 '12 at 1:33
18
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
10
An example of this passing a variable would make this a good answer. I'm still struggling after reading this.
– Goose
Jun 5 '15 at 18:44
3
@JonathanSwinney:/has no special meaning if you construct regex from string, so you don't need to escape it.//word:w*$/should benew RegExp('/word\:\w*$')
– Dávid Horváth
Jan 11 '17 at 13:52
|
show 12 more comments
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");
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");
edited Dec 17 '16 at 9:53
jcubic
33.8k30123225
33.8k30123225
answered Jan 30 '09 at 0:15
Eric WendelinEric Wendelin
30.4k85582
30.4k85582
228
If you need to use an expression like//word:w*$/, be sure to escape your backslashes:new RegExp( '\/word\:\w*$' ).
– Jonathan Swinney
Nov 9 '10 at 23:04
6
Full escape explanation: stackoverflow.com/a/6969486/151312
– CoolAJ86
Jun 3 '12 at 1:33
18
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
10
An example of this passing a variable would make this a good answer. I'm still struggling after reading this.
– Goose
Jun 5 '15 at 18:44
3
@JonathanSwinney:/has no special meaning if you construct regex from string, so you don't need to escape it.//word:w*$/should benew RegExp('/word\:\w*$')
– Dávid Horváth
Jan 11 '17 at 13:52
|
show 12 more comments
228
If you need to use an expression like//word:w*$/, be sure to escape your backslashes:new RegExp( '\/word\:\w*$' ).
– Jonathan Swinney
Nov 9 '10 at 23:04
6
Full escape explanation: stackoverflow.com/a/6969486/151312
– CoolAJ86
Jun 3 '12 at 1:33
18
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
10
An example of this passing a variable would make this a good answer. I'm still struggling after reading this.
– Goose
Jun 5 '15 at 18:44
3
@JonathanSwinney:/has no special meaning if you construct regex from string, so you don't need to escape it.//word:w*$/should benew RegExp('/word\:\w*$')
– Dávid Horváth
Jan 11 '17 at 13:52
228
228
If you need to use an expression like
//word:w*$/, be sure to escape your backslashes: new RegExp( '\/word\:\w*$' ).– Jonathan Swinney
Nov 9 '10 at 23:04
If you need to use an expression like
//word:w*$/, be sure to escape your backslashes: new RegExp( '\/word\:\w*$' ).– Jonathan Swinney
Nov 9 '10 at 23:04
6
6
Full escape explanation: stackoverflow.com/a/6969486/151312
– CoolAJ86
Jun 3 '12 at 1:33
Full escape explanation: stackoverflow.com/a/6969486/151312
– CoolAJ86
Jun 3 '12 at 1:33
18
18
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
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
10
10
An example of this passing a variable would make this a good answer. I'm still struggling after reading this.
– Goose
Jun 5 '15 at 18:44
An example of this passing a variable would make this a good answer. I'm still struggling after reading this.
– Goose
Jun 5 '15 at 18:44
3
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
@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
|
show 12 more comments
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".
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
4
developer.mozilla.org/en-US/docs/JavaScript/Guide/… offers a similar function, but they exclude-, and include=!:/.
– chbrown
Dec 15 '12 at 21:12
4
The correct term is "escape", not "quote". Just BTW.
– Lawrence Dol
Dec 4 '15 at 5:19
|
show 2 more comments
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".
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
4
developer.mozilla.org/en-US/docs/JavaScript/Guide/… offers a similar function, but they exclude-, and include=!:/.
– chbrown
Dec 15 '12 at 21:12
4
The correct term is "escape", not "quote". Just BTW.
– Lawrence Dol
Dec 4 '15 at 5:19
|
show 2 more comments
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".
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".
edited Jun 19 '12 at 8:15
Qtax
27.3k554100
27.3k554100
answered Jan 30 '09 at 1:02
GracenotesGracenotes
1,9641108
1,9641108
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
4
developer.mozilla.org/en-US/docs/JavaScript/Guide/… offers a similar function, but they exclude-, and include=!:/.
– chbrown
Dec 15 '12 at 21:12
4
The correct term is "escape", not "quote". Just BTW.
– Lawrence Dol
Dec 4 '15 at 5:19
|
show 2 more comments
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
4
developer.mozilla.org/en-US/docs/JavaScript/Guide/… offers a similar function, but they exclude-, and include=!:/.
– chbrown
Dec 15 '12 at 21:12
4
The correct term is "escape", not "quote". Just BTW.
– Lawrence Dol
Dec 4 '15 at 5:19
4
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
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
@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
(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
4
4
developer.mozilla.org/en-US/docs/JavaScript/Guide/… offers a similar function, but they exclude
-, and include =!:/.– chbrown
Dec 15 '12 at 21:12
developer.mozilla.org/en-US/docs/JavaScript/Guide/… offers a similar function, but they exclude
-, and include =!:/.– chbrown
Dec 15 '12 at 21:12
4
4
The correct term is "escape", not "quote". Just BTW.
– Lawrence Dol
Dec 4 '15 at 5:19
The correct term is "escape", not "quote". Just BTW.
– Lawrence Dol
Dec 4 '15 at 5:19
|
show 2 more comments
"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.
9
And have you measured that this is faster than regex?
– Mitar
Apr 10 '13 at 3:12
2
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.
– user1985657
Jun 12 '13 at 22:47
5
@PacMan--: bothsplitandreplacecan take either a string or aRegExpobject. The problem thatreplacehas thatsplitdoesn't is that when you use a string you only get a single replacement.
– bobince
Jun 13 '13 at 9:05
1
benchmark here: jsperf.com/replace-vs-split-join-vs-replaceall/23
– wdanda
Feb 21 '18 at 16:42
|
show 3 more comments
"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.
9
And have you measured that this is faster than regex?
– Mitar
Apr 10 '13 at 3:12
2
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.
– user1985657
Jun 12 '13 at 22:47
5
@PacMan--: bothsplitandreplacecan take either a string or aRegExpobject. The problem thatreplacehas thatsplitdoesn't is that when you use a string you only get a single replacement.
– bobince
Jun 13 '13 at 9:05
1
benchmark here: jsperf.com/replace-vs-split-join-vs-replaceall/23
– wdanda
Feb 21 '18 at 16:42
|
show 3 more comments
"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.
"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.
edited Jan 30 '18 at 11:45
Liam
16.2k1676129
16.2k1676129
answered Feb 1 '09 at 3:43
bobincebobince
443k89571770
443k89571770
9
And have you measured that this is faster than regex?
– Mitar
Apr 10 '13 at 3:12
2
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.
– user1985657
Jun 12 '13 at 22:47
5
@PacMan--: bothsplitandreplacecan take either a string or aRegExpobject. The problem thatreplacehas thatsplitdoesn't is that when you use a string you only get a single replacement.
– bobince
Jun 13 '13 at 9:05
1
benchmark here: jsperf.com/replace-vs-split-join-vs-replaceall/23
– wdanda
Feb 21 '18 at 16:42
|
show 3 more comments
9
And have you measured that this is faster than regex?
– Mitar
Apr 10 '13 at 3:12
2
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.
– user1985657
Jun 12 '13 at 22:47
5
@PacMan--: bothsplitandreplacecan take either a string or aRegExpobject. The problem thatreplacehas thatsplitdoesn't is that when you use a string you only get a single replacement.
– bobince
Jun 13 '13 at 9:05
1
benchmark here: jsperf.com/replace-vs-split-join-vs-replaceall/23
– wdanda
Feb 21 '18 at 16:42
9
9
And have you measured that this is faster than regex?
– Mitar
Apr 10 '13 at 3:12
And have you measured that this is faster than regex?
– Mitar
Apr 10 '13 at 3:12
2
2
This seems preferable, especially when needing to match on special regex characters like '.'
– Krease
Apr 24 '13 at 18:41
This seems preferable, especially when needing to match on special regex characters like '.'
– Krease
Apr 24 '13 at 18:41
1
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.
– user1985657
Jun 12 '13 at 22:47
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.
– user1985657
Jun 12 '13 at 22:47
5
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 9:05
@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 9:05
1
1
benchmark here: jsperf.com/replace-vs-split-join-vs-replaceall/23
– wdanda
Feb 21 '18 at 16:42
benchmark here: jsperf.com/replace-vs-split-join-vs-replaceall/23
– wdanda
Feb 21 '18 at 16:42
|
show 3 more comments
For anyone looking to use variable with the match method, this worked for me
var alpha = 'fig';
'food fight'.match(alpha + 'ht')[0]; // fight
Thanks, you help me lot
– kumaresan_sd
Jan 28 at 10:07
add a comment |
For anyone looking to use variable with the match method, this worked for me
var alpha = 'fig';
'food fight'.match(alpha + 'ht')[0]; // fight
Thanks, you help me lot
– kumaresan_sd
Jan 28 at 10:07
add a comment |
For anyone looking to use variable with the match method, this worked for me
var alpha = 'fig';
'food fight'.match(alpha + 'ht')[0]; // fight
For anyone looking to use variable with the match method, this worked for me
var alpha = 'fig';
'food fight'.match(alpha + 'ht')[0]; // fight
edited May 9 '15 at 17:48
answered Nov 28 '12 at 15:32
Steven PennySteven Penny
1
1
Thanks, you help me lot
– kumaresan_sd
Jan 28 at 10:07
add a comment |
Thanks, you help me lot
– kumaresan_sd
Jan 28 at 10:07
Thanks, you help me lot
– kumaresan_sd
Jan 28 at 10:07
Thanks, you help me lot
– kumaresan_sd
Jan 28 at 10:07
add a comment |
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.
15
yep, but in first example it usespatternas variable, in 2nd as a string
– vladkras
Jul 9 '13 at 4:16
1
I actually find this to be the clearest answer.
– Teekin
Aug 18 '18 at 16:17
add a comment |
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.
15
yep, but in first example it usespatternas variable, in 2nd as a string
– vladkras
Jul 9 '13 at 4:16
1
I actually find this to be the clearest answer.
– Teekin
Aug 18 '18 at 16:17
add a comment |
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.
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.
answered Jan 30 '09 at 0:19
Jeremy RutenJeremy Ruten
125k34157184
125k34157184
15
yep, but in first example it usespatternas variable, in 2nd as a string
– vladkras
Jul 9 '13 at 4:16
1
I actually find this to be the clearest answer.
– Teekin
Aug 18 '18 at 16:17
add a comment |
15
yep, but in first example it usespatternas variable, in 2nd as a string
– vladkras
Jul 9 '13 at 4:16
1
I actually find this to be the clearest answer.
– Teekin
Aug 18 '18 at 16:17
15
15
yep, but in first example it uses
pattern as variable, in 2nd as a string– vladkras
Jul 9 '13 at 4:16
yep, but in first example it uses
pattern as variable, in 2nd as a string– vladkras
Jul 9 '13 at 4:16
1
1
I actually find this to be the clearest answer.
– Teekin
Aug 18 '18 at 16:17
I actually find this to be the clearest answer.
– Teekin
Aug 18 '18 at 16:17
add a comment |
this.replace( new RegExp( replaceThis, 'g' ), withThis );
add a comment |
this.replace( new RegExp( replaceThis, 'g' ), withThis );
add a comment |
this.replace( new RegExp( replaceThis, 'g' ), withThis );
this.replace( new RegExp( replaceThis, 'g' ), withThis );
edited Jan 16 '12 at 16:22
Mike Samuel
93.2k23171214
93.2k23171214
answered Jan 30 '09 at 0:16
tvanfossontvanfosson
427k80646752
427k80646752
add a comment |
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
answered Jun 13 '18 at 2:52
JBallinJBallin
1,0341120
1,0341120
add a comment |
add a comment |
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
add a comment |
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
add a comment |
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
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
edited Feb 1 '09 at 9:28
answered Feb 1 '09 at 9:14
unigogounigogo
48948
48948
add a comment |
add a comment |
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.escapeRegexfunction. It'll take a single string
argument and escape all regex characters, making the result safe to
pass tonew 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]"
add a comment |
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.escapeRegexfunction. It'll take a single string
argument and escape all regex characters, making the result safe to
pass tonew 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]"
add a comment |
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.escapeRegexfunction. It'll take a single string
argument and escape all regex characters, making the result safe to
pass tonew 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]"
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.escapeRegexfunction. It'll take a single string
argument and escape all regex characters, making the result safe to
pass tonew 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]"
edited Jan 27 '16 at 6:24
answered Sep 14 '14 at 19:55
Salman ASalman A
180k66339431
180k66339431
add a comment |
add a comment |
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;
};
add a comment |
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;
};
add a comment |
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;
};
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;
};
answered May 8 '13 at 10:30
scriptoscripto
2,13311011
2,13311011
add a comment |
add a comment |
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("]", ">"))
add a comment |
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("]", ">"))
add a comment |
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("]", ">"))
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("]", ">"))
answered Aug 20 '13 at 12:35
MetalGodwinMetalGodwin
2,568299
2,568299
add a comment |
add a comment |
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)
add a comment |
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)
add a comment |
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)
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)
edited May 23 '17 at 12:10
Community♦
11
11
answered Jan 30 '09 at 1:02
Jason SJason S
107k135488821
107k135488821
add a comment |
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
edited Jun 5 '13 at 4:38
answered Jun 5 '13 at 4:22
Alex LiAlex Li
312
312
add a comment |
add a comment |
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!"
why a downvote? coffeescript -IS- javascript with it's own specific syntax.
– keen
Aug 26 '15 at 15:53
add a comment |
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!"
why a downvote? coffeescript -IS- javascript with it's own specific syntax.
– keen
Aug 26 '15 at 15:53
add a comment |
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!"
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!"
edited Oct 29 '15 at 15:49
answered Nov 25 '14 at 23:31
keenkeen
647710
647710
why a downvote? coffeescript -IS- javascript with it's own specific syntax.
– keen
Aug 26 '15 at 15:53
add a comment |
why a downvote? coffeescript -IS- javascript with it's own specific syntax.
– keen
Aug 26 '15 at 15:53
why a downvote? coffeescript -IS- javascript with it's own specific syntax.
– keen
Aug 26 '15 at 15:53
why a downvote? coffeescript -IS- javascript with it's own specific syntax.
– keen
Aug 26 '15 at 15:53
add a comment |
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>");
add a comment |
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>");
add a comment |
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>");
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>");
answered Jun 13 '13 at 11:13
Fareed AlnamroutiFareed Alnamrouti
20k36456
20k36456
add a comment |
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
answered Aug 16 '13 at 19:53
Ry-♦Ry-
168k40342359
168k40342359
add a comment |
add a comment |
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.
Your replace_with variable will contain the DOM element not the value itself
– Ben Taliadoros
Oct 27 '17 at 14:26
add a comment |
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.
Your replace_with variable will contain the DOM element not the value itself
– Ben Taliadoros
Oct 27 '17 at 14:26
add a comment |
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.
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.
edited Jul 12 '18 at 6:56
Saikat
2,63553760
2,63553760
answered Oct 27 '15 at 5:56
Ajit HogadeAjit Hogade
610520
610520
Your replace_with variable will contain the DOM element not the value itself
– Ben Taliadoros
Oct 27 '17 at 14:26
add a comment |
Your replace_with variable will contain the DOM element not the value itself
– Ben Taliadoros
Oct 27 '17 at 14:26
Your replace_with variable will contain the DOM element not the value itself
– Ben Taliadoros
Oct 27 '17 at 14:26
Your replace_with variable will contain the DOM element not the value itself
– Ben Taliadoros
Oct 27 '17 at 14:26
add a comment |
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>
You're overwriting a closure variable, no need to usevarhere. Also, if you passbor1it would break.
– CyberAP
Nov 6 '18 at 19:00
add a comment |
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>
You're overwriting a closure variable, no need to usevarhere. Also, if you passbor1it would break.
– CyberAP
Nov 6 '18 at 19:00
add a comment |
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>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>$("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>$("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>answered Oct 18 '18 at 18:37
Paul JonesPaul Jones
321311
321311
You're overwriting a closure variable, no need to usevarhere. Also, if you passbor1it would break.
– CyberAP
Nov 6 '18 at 19:00
add a comment |
You're overwriting a closure variable, no need to usevarhere. Also, if you passbor1it would break.
– CyberAP
Nov 6 '18 at 19:00
You're overwriting a closure variable, no need to use
var here. Also, if you pass b or 1 it would break.– CyberAP
Nov 6 '18 at 19:00
You're overwriting a closure variable, no need to use
var here. Also, if you pass b or 1 it would break.– CyberAP
Nov 6 '18 at 19:00
add a comment |
protected by Community♦ Sep 19 '18 at 9:52
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
3
Note that we're currently working on adding this functionality to JavaScript if you have an opinion about it please join the discussion.
– Benjamin Gruenbaum
Jun 23 '15 at 11:38