Home > OS >  How to repeat a word based on the given number?
How to repeat a word based on the given number?

Time:08-10

Example, we have this string 1 jar 2 melon 5 ice it will turn into jar melon melon ice ice ice ice ice. Another example, 2 dress 1 mouse 3 jar 1 phone > dress dress mouse jar jar jar phone. How can I do that in javascript?

CodePudding user response:

Done with JS RexExp:

let str = "1 jar 2 beers 3 melons"
str.replace(/([1-9]\d*)\s(\w )/g, (substring, arg1, arg2)=>{
  return (arg2 " ").repeat(parseInt(arg1)).slice(0, -1); // replaces substring with arg2 repeated `parseInt(arg1)` times
}); // jar beers beers melons melons melons

CodePudding user response:

Assuming you are innocently desiring to learn coding and not trying to do some random shortcut:

Step 1: We could use regex to split the string and mess with it from there:

const str = "1 jar 2 melon 5 ice";
let arr = str.split(/ (?=\d)/g); // match spaces that are proceeded by a number
// ["1 jar", "2 melon", "5 ice"]

Step 2: Extract the numbers by splitting again:

arr = arr.map(i => {
  i = i.split(" ");
  const num =  i[0]; // cast string to number
  const word = i.slice(1).join(" "); // join rest of the string
  return (word   " ").repeat(num).trim();
});

Step 3: Build the result:

const result = arr.join(" ");

At the end, your code would look like:

const str = "1 jar 2 melon 5 ice";
let arr = str.split(/ (?=\d)/g);
arr = arr.map(i => {
  i = i.split(" ");
  const num =  i[0];
  const word = i.slice(1).join(" ");
  return (word   " ").repeat(num).trim();
});

const result = arr.join(" ");

console.log(result);

  • Related