我有一个字符串
var stringP= "hi".rand(1,10)." my".rand(10,100)."name is ".rand(23,54).rand(1,4)
模式是
rand(from,to)
需要获取
hi5 my54name is 335
可以使用类似的东西吗?
stringP.replace(/rand(*,*)/g, function(match){
return match.replace(rand(*,*),Math.floor(Math.random() * (to - from + 1) + from));
});
最佳答案
是的,几乎一切皆有可能。然而,您想使用[一个!]正确的 regular expression ,以及适当的 replace function :
stringP.replace(/rand\((\d+),(\d+)\)/g, function(match, from, to) {
from = parseInt(from, 10);
to = parseInt(to, 10);
return Math.floor(Math.random() * (to - from + 1) + from);
});
关于javascript - 每次在字符串中找到匹配项时都会运行该函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14616024/