cti*_*y79 3 javascript typescript
我有以下函数用随机数替换字符串出现.我目前用相同的随机数替换字符串.我需要一个函数来替换每个实例一个唯一的数字.这就是我所拥有的.
尝试澄清:
我想找到的所有匹配'},{和替换它与},"random":{地方random是每次出现的唯一的整数.
result = this.replaceAll(result, '},{', `},"${this.getRandomInt(1, 2000)}":{`);
private getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
private replaceAll(str, find, replace) {
return str.replace(new RegExp(this.escapeRegExp(find), 'g'), replace);
}
private escapeRegExp(str) {
return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
Run Code Online (Sandbox Code Playgroud)
目前结果是有效的
},"1340":{"expense_category_id":"63","amount":3},"1340":{"expense_category_id":"62","amount":3}}}}
Run Code Online (Sandbox Code Playgroud)
1340不应该重复
编辑:替换all之前的结果值是:
},{"expense_category_id":"63","amount":3},{"expense_category_id":"62","amount":3}}}}
Run Code Online (Sandbox Code Playgroud)
将函数传递给replace()第二个参数,如下所示:
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function replaceAll(str, find, replace) {
return str.replace(new RegExp(this.escapeRegExp(find), 'g'), replace);
}
function escapeRegExp(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);Run Code Online (Sandbox Code Playgroud)
我不确定为什么,但它似乎使用为第一次迭代生成的相同字符串用于后续迭代.使用函数,您可以强制它每次运行.
| 归档时间: |
|
| 查看次数: |
4280 次 |
| 最近记录: |