There is a line:

let formula = 'A+B*(ABS(BA))' 

And there is an object:

 let replace_func = { A: 'C+5', B: 'D-2' } 

It is necessary to replace the variables in the string 'formula' with the elements 'replace_func' according to the keys, so that it turns out:

 let result = '(C+5)+(D-2)*(ABS((D-2)-(C+5)))' 

To avoid replacing the ABS () function in the name, it was decided to use the regular schedule:

 let replace_regx = new RegExp('[\/\*\-\+\(]?' + cur_key + '[\/\*\-\+\)]?') formula = formula.replace(replace_regx, replace_func[cur_key]) 

But on the regular schedule, not only the name of the variable is replaced, but also the signs before and after it (eg. Instead of 'A' is taken as '-A)' )

How can I solve this problem? In regulars is not strong, so I ask for help)

  • variable only single letter? - Grundy
  • @Grundy, only single letters - Kirill Semenov

1 answer 1

Since the variable in this case is a word from one letter, you can use \b - meaning the word boundary.

In this case, the regular expression takes the form:

 /\b\w\b/g 

When using this expression in the replace method, a separate letter will be passed to the handler function, which will be a possible variable for replacement.

You can return from the handler function either the value corresponding to the replacement, or, if the variable is not in the list of substitutions, the matching value itself.

And the general challenge will become more general.

 let formula = 'A+B*(ABS(BA))' let replace_func = { A: 'C+5', B: 'D-2' } console.log(formula); let result = formula.replace(/\b\w\b/g, $0 => `(${replace_func[$0] || $0})`); console.log(result);