0

I have the current function:

function replaceValue(v) {
  const firstRegex = new RegExp('hello', 'g');
  const secondRegex = new RegExp('bye', 'g');

  return v.replace(firstRegex, '@').replace(secondRegex, '#');
}

However, now I want to add even more regex, and I want to have a datastructure that looks like this:

const regexStorage = [{
 value: '@',
 replace: 'hello',
}, {
 value: '#',
 replace: 'bye',
}]

I can't figure out a way to use that regexStorage to dynamically add as many replaces as they exist in the array for a given value.

I've got to this:

function replaceValue(v) {
  const firstRegex = new RegExp(regexStorage[0].replace, 'g');
  const secondRegex = new RegExp(regexStorage[1].replace, 'g');

  return v.replace(firstRegex, regexStorage[0].value).replace(secondRegex, regexStorage[1].value);
}

But that's just using the storage. I wonder how I can do this dynamically.

2 Answers 2

2

In JS, you can write a one-line reduce (which was designed for this exact scenario of operating on an array but returning a single value) (mdn) loop as:

const regexStorage = [{
 value: '@',
 replace: 'hello',
}, {
 value: '#',
 replace: 'bye',
}];

let replaceValue = v => regexStorage.reduce((v, {value, replace}) => v.replace(new RegExp(replace, 'g'), value), v);

let str = 'hi hello bye bi hello';
console.log(replaceValue(str));
console.log(str);

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

7 Comments

Would this change the original v value?
No. JS, like most languages including Java and C++, passes primitives by value. Updated snippet to exemplify the unchanged argument value.
I'm confused on why is the argument named v and also the value in the reduce function is called v.
You could name them different, but since they represent the same value, it makes sense to keep the same name. It's like if you had a function purchase(cost), which then called function chargeCreditCard(cost) and function calcTax(cost), all 3 functions have the same param name because it represents the same thing.
Alternatively, you could have different names: let replaceValue = str => regexStorage.reduce((v, {value, replace}) => v.replace(new RegExp(replace, 'g'), value), str);
|
1

You can just loop through your regex storage

const regexStorage = [
  {
   value: '@',
   replace: 'hello',
  }, 
  {
   value: '#',
   replace: 'bye',
  }
]


function replaceValue(v) {
  for(var i = 0; i < regexStorage.length; i++){
    v = v.replace(new RegExp(regexStorage[i].replace, "g"), regexStorage[i].value);
  }
  return v;
}
var data = "hello, my name is andam. bye.";
console.log(data);
console.log(replaceValue(data));

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.