Thread: regex variable
View Single Post
Old 12-08-2012, 01:07 PM   PM User | #14
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,037
Thanks: 197
Thanked 2,411 Times in 2,389 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
Quote:
Originally Posted by 007julien View Post
After a few tests the \ should be treated separately.
The following method may be helpful
Code:
<script type="text/javascript">
String.prototype.toRegExp=function(){return this.replace(/\\/g,'\\\\').replace(/(\[|\^|\$|\.|\||\?|\*|\+|\(|\))/g,'\\$1')}

//Example of use with all the «meta»characters
var something="[\\^$.|?*+()";// the \ is to escape in this string.

alert(("foo"+something+"bar").replace(new RegExp(something.toRegExp(),'g'),'')); //=>"foobar"
rnd me beat you to the draw!

http://www.codingforums.com/showthread.php?p=1298212
__________________

All the code given in this post has been tested and is intended to address the question asked.
Unless stated otherwise it is not just a demonstration.
Philip M is offline   Reply With Quote