javascript - 每次在字符串中找到匹配项时都会运行该函数

标签 javascript replace match

我有一个字符串

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/

相关文章:

python - 正则表达式或用通配符替换()?

python - 根据匹配值合并 2 个字典列表,否则保持原始?

delphi - 如何在odt Open Office文档中搜索和替换?

javascript - 如何加载配置json作为环境变量nodejs

如果找不到数组中的元素,Javascript 函数会尝试该元素

javascript将字符串转换和分解为数字

Java 替换方法不适用于 ©

r - 在 data.table 的 i 中使用匹配

mysql - 为什么 SQl MATCH AGAINST 找不到结果中只有 3 个字符的结果?

javascript - virtual <input type ="file"> 元素 - 不可靠的 onchange 事件 - 为什么?