How do you use a variable in a regular expression?
up vote
1036
down vote
favorite
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 |
up vote
1036
down vote
favorite
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 |
up vote
1036
down vote
favorite
up vote
1036
down vote
favorite
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 Grubbs
13.8k266072
13.8k266072
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
up vote
1456
down vote
accepted
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");
221
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
5
Full escape explanation: stackoverflow.com/a/6969486/151312
– CoolAJ86
Jun 3 '12 at 1:33
17
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
9
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 10 more comments
up vote
173
down vote
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
up vote
91
down vote
"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.
5
Cool idea, wouldn't have thought of doing that!
– devios1
May 31 '12 at 19:01
8
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--: bothsplit
andreplace
can take either a string or aRegExp
object. The problem thatreplace
has thatsplit
doesn't is that when you use a string you only get a single replacement.
– bobince
Jun 13 '13 at 9:05
|
show 4 more comments
up vote
28
down vote
For anyone looking to use variable with the match method, this worked for me
var alpha = 'fig';
'food fight'.match(alpha + 'ht')[0]; // fight
add a comment |
up vote
24
down vote
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.
12
yep, but in first example it usespattern
as variable, in 2nd as a string
– vladkras
Jul 9 '13 at 4:16
I actually find this to be the clearest answer.
– Teekin
Aug 18 at 16:17
add a comment |
up vote
14
down vote
this.replace( new RegExp( replaceThis, 'g' ), withThis );
add a comment |
up vote
9
down vote
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 |
up vote
7
down vote
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 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 |
up vote
6
down vote
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 |
up vote
4
down vote
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 |
up vote
3
down vote
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 |
up vote
3
down vote
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 |
up vote
3
down vote
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 |
up vote
3
down vote
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 |
up vote
1
down vote
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 |
up vote
1
down vote
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 |
up vote
1
down vote
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 |
up vote
0
down vote
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 usevar
here. Also, if you passb
or1
it would break.
– CyberAP
Nov 6 at 19:00
add a comment |
protected by Community♦ Sep 19 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
up vote
1456
down vote
accepted
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");
221
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
5
Full escape explanation: stackoverflow.com/a/6969486/151312
– CoolAJ86
Jun 3 '12 at 1:33
17
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
9
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 10 more comments
up vote
1456
down vote
accepted
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");
221
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
5
Full escape explanation: stackoverflow.com/a/6969486/151312
– CoolAJ86
Jun 3 '12 at 1:33
17
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
9
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 10 more comments
up vote
1456
down vote
accepted
up vote
1456
down vote
accepted
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.1k29117221
33.1k29117221
answered Jan 30 '09 at 0:15
Eric Wendelin
29.5k85482
29.5k85482
221
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
5
Full escape explanation: stackoverflow.com/a/6969486/151312
– CoolAJ86
Jun 3 '12 at 1:33
17
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
9
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 10 more comments
221
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
5
Full escape explanation: stackoverflow.com/a/6969486/151312
– CoolAJ86
Jun 3 '12 at 1:33
17
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
9
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
221
221
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
5
5
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
17
17
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
9
9
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 10 more comments
up vote
173
down vote
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
up vote
173
down vote
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
up vote
173
down vote
up vote
173
down vote
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
27k55297
27k55297
answered Jan 30 '09 at 1:02
Gracenotes
1,9141108
1,9141108
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
up vote
91
down vote
"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.
5
Cool idea, wouldn't have thought of doing that!
– devios1
May 31 '12 at 19:01
8
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--: bothsplit
andreplace
can take either a string or aRegExp
object. The problem thatreplace
has thatsplit
doesn't is that when you use a string you only get a single replacement.
– bobince
Jun 13 '13 at 9:05
|
show 4 more comments
up vote
91
down vote
"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.
5
Cool idea, wouldn't have thought of doing that!
– devios1
May 31 '12 at 19:01
8
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--: bothsplit
andreplace
can take either a string or aRegExp
object. The problem thatreplace
has thatsplit
doesn't is that when you use a string you only get a single replacement.
– bobince
Jun 13 '13 at 9:05
|
show 4 more comments
up vote
91
down vote
up vote
91
down vote
"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 at 11:45
Liam
15.7k1675125
15.7k1675125
answered Feb 1 '09 at 3:43
bobince
438k88563763
438k88563763
5
Cool idea, wouldn't have thought of doing that!
– devios1
May 31 '12 at 19:01
8
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--: bothsplit
andreplace
can take either a string or aRegExp
object. The problem thatreplace
has thatsplit
doesn't is that when you use a string you only get a single replacement.
– bobince
Jun 13 '13 at 9:05
|
show 4 more comments
5
Cool idea, wouldn't have thought of doing that!
– devios1
May 31 '12 at 19:01
8
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--: bothsplit
andreplace
can take either a string or aRegExp
object. The problem thatreplace
has thatsplit
doesn't is that when you use a string you only get a single replacement.
– bobince
Jun 13 '13 at 9:05
5
5
Cool idea, wouldn't have thought of doing that!
– devios1
May 31 '12 at 19:01
Cool idea, wouldn't have thought of doing that!
– devios1
May 31 '12 at 19:01
8
8
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
|
show 4 more comments
up vote
28
down vote
For anyone looking to use variable with the match method, this worked for me
var alpha = 'fig';
'food fight'.match(alpha + 'ht')[0]; // fight
add a comment |
up vote
28
down vote
For anyone looking to use variable with the match method, this worked for me
var alpha = 'fig';
'food fight'.match(alpha + 'ht')[0]; // fight
add a comment |
up vote
28
down vote
up vote
28
down vote
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 Penny
1
1
add a comment |
add a comment |
up vote
24
down vote
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.
12
yep, but in first example it usespattern
as variable, in 2nd as a string
– vladkras
Jul 9 '13 at 4:16
I actually find this to be the clearest answer.
– Teekin
Aug 18 at 16:17
add a comment |
up vote
24
down vote
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.
12
yep, but in first example it usespattern
as variable, in 2nd as a string
– vladkras
Jul 9 '13 at 4:16
I actually find this to be the clearest answer.
– Teekin
Aug 18 at 16:17
add a comment |
up vote
24
down vote
up vote
24
down vote
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 Ruten
122k34155184
122k34155184
12
yep, but in first example it usespattern
as variable, in 2nd as a string
– vladkras
Jul 9 '13 at 4:16
I actually find this to be the clearest answer.
– Teekin
Aug 18 at 16:17
add a comment |
12
yep, but in first example it usespattern
as variable, in 2nd as a string
– vladkras
Jul 9 '13 at 4:16
I actually find this to be the clearest answer.
– Teekin
Aug 18 at 16:17
12
12
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
I actually find this to be the clearest answer.
– Teekin
Aug 18 at 16:17
I actually find this to be the clearest answer.
– Teekin
Aug 18 at 16:17
add a comment |
up vote
14
down vote
this.replace( new RegExp( replaceThis, 'g' ), withThis );
add a comment |
up vote
14
down vote
this.replace( new RegExp( replaceThis, 'g' ), withThis );
add a comment |
up vote
14
down vote
up vote
14
down vote
this.replace( new RegExp( replaceThis, 'g' ), withThis );
this.replace( new RegExp( replaceThis, 'g' ), withThis );
edited Jan 16 '12 at 16:22
Mike Samuel
91.8k23169212
91.8k23169212
answered Jan 30 '09 at 0:16
tvanfosson
421k78640749
421k78640749
add a comment |
add a comment |
up vote
9
down vote
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 |
up vote
9
down vote
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 |
up vote
9
down vote
up vote
9
down vote
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
unigogo
47948
47948
add a comment |
add a comment |
up vote
7
down vote
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 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 |
up vote
7
down vote
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 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 |
up vote
7
down vote
up vote
7
down vote
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 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.escapeRegex
function. 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 A
171k65328414
171k65328414
add a comment |
add a comment |
up vote
6
down vote
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 |
up vote
6
down vote
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 |
up vote
6
down vote
up vote
6
down vote
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 at 2:52
JBallin
8431019
8431019
add a comment |
add a comment |
up vote
4
down vote
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 |
up vote
4
down vote
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 |
up vote
4
down vote
up vote
4
down vote
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
scripto
2,1331911
2,1331911
add a comment |
add a comment |
up vote
3
down vote
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 |
up vote
3
down vote
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 |
up vote
3
down vote
up vote
3
down vote
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 S
106k134475813
106k134475813
add a comment |
add a comment |
up vote
3
down vote
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 |
up vote
3
down vote
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 |
up vote
3
down vote
up vote
3
down vote
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 Li
312
312
add a comment |
add a comment |
up vote
3
down vote
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 |
up vote
3
down vote
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 |
up vote
3
down vote
up vote
3
down vote
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
MetalGodwin
2,468299
2,468299
add a comment |
add a comment |
up vote
3
down vote
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 |
up vote
3
down vote
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 |
up vote
3
down vote
up vote
3
down vote
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
keen
637710
637710
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 |
up vote
1
down vote
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 |
up vote
1
down vote
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 |
up vote
1
down vote
up vote
1
down vote
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 Alnamrouti
19.4k26055
19.4k26055
add a comment |
add a comment |
up vote
1
down vote
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 |
up vote
1
down vote
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 |
up vote
1
down vote
up vote
1
down vote
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-♦
165k37336357
165k37336357
add a comment |
add a comment |
up vote
1
down vote
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 |
up vote
1
down vote
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 |
up vote
1
down vote
up vote
1
down vote
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 at 6:56
Saikat
2,31553255
2,31553255
answered Oct 27 '15 at 5:56
Ajit Hogade
609520
609520
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 |
up vote
0
down vote
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 usevar
here. Also, if you passb
or1
it would break.
– CyberAP
Nov 6 at 19:00
add a comment |
up vote
0
down vote
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 usevar
here. Also, if you passb
or1
it would break.
– CyberAP
Nov 6 at 19:00
add a comment |
up vote
0
down vote
up vote
0
down vote
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 at 18:37
Paul Jones
178210
178210
You're overwriting a closure variable, no need to usevar
here. Also, if you passb
or1
it would break.
– CyberAP
Nov 6 at 19:00
add a comment |
You're overwriting a closure variable, no need to usevar
here. Also, if you passb
or1
it would break.
– CyberAP
Nov 6 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 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 at 19:00
add a comment |
protected by Community♦ Sep 19 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