Skip to content Skip to sidebar Skip to footer

Typescript/javascript: Replace All String Occurrences With Random Number

I have the following function that replaces a string occurence with a random number. What I have currently replaces the string with the same random number. I need a function that

Solution 1:

Pass a function to the replace() second parameter like this:

functiongetRandomInt(min, max) {
  returnMath.floor(Math.random() * (max - min + 1)) + min;
}

functionreplaceAll(str, find, replace) {
  return str.replace(newRegExp(this.escapeRegExp(find), 'g'), replace);
}

functionescapeRegExp(str) {
  return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}

var input = '},{"expense_category_id":"63","amount":3},{"expense_category_id":"62","amount":3}}}}',
    result = replaceAll(input, '},{', (x =>'},"' + getRandomInt(1, 2000) + '":{'));

console.log(result);

I'm not sure why, but it seems that it uses the same string generated for the first iteration for subsequent iterations. With a function, you force it to run everytime.

Solution 2:

Your replace call is wrong. You're passing in a string, you should be passing in a function that creates the number, not the result of the number itself.

let result = "{A},{B},{C}";
    result = replaceAll(result, '},{', () => { return`},"${this.getRandomInt(1, 2000)}":{` });
    console.log(result);
    
    functiongetRandomInt(min, max) {
      returnMath.floor(Math.random() * (max - min + 1)) + min;
    }
    
    functionreplaceAll(str, find, replace) {
      return str.replace(newRegExp(this.escapeRegExp(find), 'g'), replace);
    }
    
    functionescapeRegExp(str) {
      return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
    }

Post a Comment for "Typescript/javascript: Replace All String Occurrences With Random Number"