0

How to generate a new random string each time in a given text string a regular expression is satisfied ?

I use Math.random().toString(36).substr(5,5) to generate a random string but each time a regex is satisfied in my file text, it is replaced (with the method replace() ) by the same random string

14th May 2021, 11:50 AM
Adrien Linares
Adrien Linares - avatar
2 Answers
0
Do you recall Math.random() everytime it is satisfied or only on the beginning of you program?
14th May 2021, 5:29 PM
Nico Ruder
Nico Ruder - avatar
0
use replace with a function as second argument (wich should return a random string), else second argument is evaluated only once for every matchs: str.replace(regexp,Math.random().toString(36).substr(5,5)); // replace all matchs by same random string str.replace(regexp,() => Math.random().toString(36).substr(5,5)); // replace all match by different random strings https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
14th May 2021, 5:45 PM
visph
visph - avatar