I am getting API response like this.
{
"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"
]
}
Here I should search if I have %[number] 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?
CodePudding user response:
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))
CodePudding user response:
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));
CodePudding user response:
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]
}
CodePudding user response:
You can also use template litterals. See the link below.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals