Home > front end >  Replace array values in string and make new string as per the values
Replace array values in string and make new string as per the values

Time:10-19

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;

CodePudding user response:

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);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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']

CodePudding user response:

A simple way of achieving this is by looping through the range array and pushing the desired strings to a new array.

var range = [25, 50, 100, 125], w1 = 2, strings = [];

for(index of range.keys()){ 
  strings.push(`${w1}   ${range[index]}`);
  console.log(`string${index 1}: ${strings[index]}`);
}
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related