Home > Back-end >  How to replace matched values based on ther index .replace() javascript?
How to replace matched values based on ther index .replace() javascript?

Time:12-25

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:

  • first "#" = value[0]
  • second "#" = value[1]

end key must look (10-15)% chance to gain Unholy Might for 3 seconds on Kill

CodePudding user response:

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));

CodePudding user response:

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.

CodePudding user response:

This logic will work. Make it dynamic. First line: first # will replace by 10, Second line: secont # replace by 15

data['key'].replaceMatch('#', data.value[0], 0); data['key'].replaceMatch('#', data.value[1], 1);

  • Related