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, ['.', '-'], '_')
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, ['.', '-'], '_'),
}