I have an object
{
key: "#% chance to gain Unholy Might for # seconds on Kill",
value: [
[10, 15],
[3, 3]
]
}
I need to replace key "#" in order:
end key must look (10-15)% chance to gain Unholy Might for 3 seconds on Kill
You need to iterate over the values using Array.prototype.reduce(). Then for every value update the text using String.prototype.replace():
const data = {
key: "#% chance to gain Unholy Might for # seconds on Kill",
value: [
[10, 15],
[3, 3]
]
};
const replateBy = (text, token, values) => {
return values.reduce((text, [a,b])=> text.replace(token, `${a===b ? a: `(${a}-${b})`}`), text);
}
console.log(replateBy(data.key, "#", data.value));
The simplest way to do this is with a replace. Since the first # is followed by a percentage sign we can just replace #% to start off with, which then leaves us with just the last # to replace.
const data = {
key: "#% chance to gain Unholy Might for # seconds on Kill",
value: [
[10, 15],
[3, 3]
]
}
// First we replace the #% with the actual percentage
const stringWithPercentage = data.key.replace('#%', `(${data.value[0][0]}-${data.value[0][1]})%`)
// Then we can use that value and replace the last # with the seconds
const stringWithSeconds = stringWithPercentage.replace('#', data.value[1][0])
console.log(stringWithSeconds)
There are several ways of achieving this depending on your needs and your willingness to change the data structure.