I have one array which is range and on string which is test. Now I want to replace my range array values with {q1} and replace {w1} with it's values. I added Expected output for my scenario
let range = [25, 50, 100, 125];
let w1 = 2
let test = '{w1} + {q1}'
Expected output
let string1 = 2 + 25;
let string2 = 2 + 50;
let string3 = 2 + 100;
let string4 = 2 + 125;
const range = [25, 50, 100, 125];
const w1 = 2;
const result = range.map(x=> w1.toString() + " + " + x.toString());
const range = [25, 50, 100, 125];
const w1 = 2;
const result = range.map((x) => w1.toString() + " + " + x.toString());
console.log("res", result);
You can simple achieve this using map and array destructuring assignment.
let range = [25, 50, 100, 125];
let w1 = 2;
const [string1, string2, string3, string4] = range.map(r => `${w1} + ${r}`);
console.log(string1);
console.log(string2);
console.log(string3);
console.log(string4);
You can replace string parts using String.prototype.replace() like this:
const range = [25, 50, 100, 125];
const w1 = 2;
range.map(value => '{w1} + {q1}'.replace('{w1}', w1).replace('{q1}', value));
// ['2 + 25', '2 + 50', '2 + 100', '2 + 125']
But it's a bad practise. Much better to use string interpolation via Template literals like this:
const range = [25, 50, 100, 125];
const w1 = 2;
range.map(value => `${w1} + ${value}`);
// ['2 + 25', '2 + 50', '2 + 100', '2 + 125']