Skip to content
Advertisement

Replace text starting “@” with respetive variables in Object – Javascript

I made this code trying to reproduce what i want to do in my Node JS API. I have “message” Array and “valueList” Object and i need to replace all text with “@” than have name of variables in “valueList” Object.

JavaScript

If i create one more variable in valueList i need to put one more .map in message, is possible to get automatically all object to replace all “message” ? i’m trying to do that, Thanks.

Advertisement

Answer

Another option is to create a dynamic regex with a capture group, and use an alternation | joining the keys from Object.keys(valueList) and use replace with a function.

In the replace function, you an index into the valueList object using the value of group 1 which will be either myname or myname or botname

The assembled regex looks like this and uses the global flag to replace all occurrences.

JavaScript

The pattern matches:

  • @ Match literally
  • (myname|city|botname) Capture group 1, match any of the alternatives (referenced by g1 in the code for the replacement)
  • b A word boundary to prevent a partial match

JavaScript
Advertisement