7

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?

0

1 Answer 1

16

Use the source (Luke) property.

function addBarElegant(re) {
  var reString = re.source;
  return new RegExp(reString + "bar", re.flags);
}
console.log(addBarElegant(/foo/));

Sign up to request clarification or add additional context in comments.

1 Comment

Would we be complete with new RegExp(re.source, re.flags)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.