1

How can I replace multiple chars in a string?

My current strategy is to nest the stdlib functions:

tst.jsonnet:

local tst = '0-1.2';

{
  tst: std.strReplace(std.strReplace(tst, '.', '_'), '-', '_'),
}

output:

> ./jsonnet tst.jsonnet
{
   "tst": "0_1_2"
}

I would love to be able to use the function, something like:

std_name(tst, ['.', '-'], '_')
NarūnasK
  • 4,564
  • 8
  • 50
  • 76

1 Answers1

1

Unfortunately jsonnet doesn't support regex (which would greatly help with this use-case), nevertheless you can write your own function implementing your std_name() (I named it strReplaceMany() in below code):

local tst = '0-1.2';

// Loop over fromArray (of strings), running std.stdReplace()
local strReplaceMany(str, fromArray, to) = std.foldl(
  function(retStr, from) std.strReplace(retStr, from, to),
  fromArray,
  str
);
{
  tst: strReplaceMany(tst, ['.', '-'], '_'),
}
jjo
  • 2,595
  • 1
  • 8
  • 16