Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify a JavaScript RegExp pattern

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?

like image 374
Bo Borgerson Avatar asked Jul 16 '26 09:07

Bo Borgerson


1 Answers

Use the source (Luke) property.

function addBarElegant(re) {
  var reString = re.source;
  return new RegExp(reString + "bar", re.flags);
}
console.log(addBarElegant(/foo/));
like image 75
Barmar Avatar answered Jul 18 '26 22:07

Barmar