Replacing Multiple Characters / Building Custom Function

Hi Everyone,
I have a requirement to perform multiple replacement such as
A/J converts to 1,
B/K converts to 2,
{/} converts to 0 and so on.
All these have to work for one input string. Instead of writing multiple replace functions can this be done in one single function or can I write some reusable function to be used in all the pipelines in my project?

Thanks in advance!

The replace() method on strings does support passing a callback function (although we missed updating the documentation to reflect this). It should behave similarly to the JavaScript version of the method.

The regex, /[A-R]/g, should match the characters you’re interested in and at all positions in the input string. You can then write an arrow function that will receive the matched substring and the result of the function will be used as the replacement string. The function can use the charCodeAt() string method to get the ASCII number of a character, which we then subtract ‘A’ from to get close to the value you’re interested in. Since the value wraps around when ‘J’ is reached, we do a ‘% 9’, and then finally add one to get the final result. Here’s the full expression:

$value.replace(/[A-R]/g, m => ((m.charCodeAt(0) - 'A'.charCodeAt(0)) % 9) + 1)

You can wrap this in a function and put it in an expression library in order to reuse it across pipelines.

Alternatively, you can use the new match operator if you had more complex cases for how to do the replacements. Here’s an abbreviated example that handles replacing ‘ABJK’ with 1 and 2:

$value.replace(/[A-R]/g, m => match m {
    'A'|'J' => 1,
    'B'|'K' => 2,
    /* Add remaining cases... */
    _ => m

Here’s an export of the pipeline with both expressions:

ReplaceFunc_2018_08_15.slp (5.2 KB)

Thank you so much! That helped! :slight_smile: :+1: