1

I have the following

astring.replace(/(someregex/g, "replacementstring.$1")

I'd like to store it as some sort of object, so I can call it in the future. The obvious solution is to store it as two variables someregex and replacementstring and call it in the future as astring.replace(someregex, replacementstring + '.$1') But that seems really clunky to me.

Is there anyway to store the string replacement in a more concise manner? My current idea is to store .replace(/someregex/g, "replacementstring.$1") as a string called stringreplacement and use eval('astring' + stringreplacement). But that seems silly.

1
  • Well, for the regex part you could store it as an actual RegExp object. var pattern = new RegExp("someregex", "g"); Commented Jul 23, 2018 at 22:57

1 Answer 1

3

You could use currying to define a function where some variables are already pre-defined.

For example:

function replace(find, replace) {
  return function (string) {
    return string.replace(find, replace);
  }
}

const replacer = replace(/hello/gi, "G'day");

console.log(replacer('hello fubar'));

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

Comments

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.