I want to create a new RegExp object by modifying the pattern from another RegExp object.
The output of RegExp.prototype.toString() includes leading and trailing slashes.
// This is nice and clean, but produces incorrect output.
function addBarWrong(re) {
return new RegExp(re+"bar");
}
addBarWrong(new RegExp("foo")); // -> /\/foo\/bar/
My naive approach is pretty inelegant.
// This is unpleasant to look at, but produces correct output.
function addBarUgly(re) {
var reString = re.toString();
reString = reString.substr(1, reString.length - 2);
return new RegExp(reString+"bar");
}
addBarUgly(new RegExp("foo")); // -> /foobar/
Surely there's a better way. What is the clean solution here?