Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

194
Views
How to replace matched values based on ther index .replace() javascript?

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

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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

about 4 years ago · Santiago Trujillo Report

0

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.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!