Mohammed Ismail
Mohammed Ismail

Reputation: 304

How do I replace %<string> with the parameters

I am getting API response like this.

{
  "message": "The password needs at least %1 characters. Password should be having %param2 special characters in it. Create a new password and try again.",
  "parameters": [
    "8",
    "param2test"
  ]
}

Here I should search if I have %[string] in the response, if its there I need to replace %1 with the first array element of parameters, %2 with second and so on. There could be n number of parameters. How can I do this in React?

Upvotes: 0

Views: 107

Answers (3)

sonu sharma
sonu sharma

Reputation: 39

const obj = {
  "message": "The password needs at least %1 characters. Password should be having %2 special characters in it. Create a new password and try again.",
  "parameters": [
    "8",
    "2"
  ]
};


function change({ message, parameters }) {
  let str = message;

  message.match(/(%[0-9]+)/g).forEach((item, i) => {
    str = str.replace(item, parameters[i]);
  })

  return str;
}

console.log(change(obj));

Upvotes: 1

Reifocs
Reifocs

Reputation: 746

const r = {
    "message": "The password needs at least %1 characters. Password should be having %2 special characters in it. Create a new password and try again.",
    "parameters": [
        "8",
        "2"
    ]
}

const parameterizedString = (...args) => {
    const [str, ...params] = args;
    return str.replace(/%\d+/g, matchedStr => {
        const variableIndex = matchedStr.replace("%", "") - 1;
        return params[variableIndex];
    });
}
console.log(parameterizedString(r.message, ...r.parameters))

Upvotes: 1

PeterT
PeterT

Reputation: 517

You can try this:

const obj = {
  "message": "The password needs at least %1 characters. Password should be having %2 special characters in it. Create a new password and try again.",
  "parameters": [
    "8",
    "2"
  ]
}

const regex = /%\d/g;
function f(match){
  const m = Number(match.slice(1))
  return obj.parameters[m-1]
}

Upvotes: 0

Related Questions