Thread: regex variable
View Single Post
Old 12-08-2012, 01:03 PM   PM User | #13
007julien
Regular Coder

 
Join Date: May 2012
Location: France
Posts: 115
Thanks: 0
Thanked 17 Times in 15 Posts
007julien is an unknown quantity at this point
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"
007julien is offline   Reply With Quote