2 回答
TA贡献1830条经验 获得超3个赞
仅使用您提供的两个项目作为输入(字符串和带有ndn=(n)单词种类的数组),您可以进行如下操作:
let str = ' I roll 1d3 and 2d4+3 and 1d3 also 1d8 and 1d8 dice ';
let array = [ "1d3:[2]=2" , "2d4:[1,2]+3=6" , "1d3:[1]=1", "1d8:[7]=7", "1d8:[5]=5"];
let i = 0;
for (let item of array) {
let find = item.replace(/:.*\]|=.*/g, "");
i = str.indexOf(find, i);
str = str.slice(0, i) + item + str.slice(i + find.length);
i += item.length;
}
console.log(str);
假设数组是格式良好的,即这些项目确实是从字符串中正确导出的,并且等号之前的所有字符串部分(如“1d3”)都出现在字符串中。
请注意,字符串是不可变的,因此您不能真正改变字符串。唯一的方法是创建一个新字符串并将其分配回同一个变量。但这不是突变;那就是分配一个新的字符串。
TA贡献1799条经验 获得超9个赞
如果我了解您的要求,我认为您的解决方案过于复杂。我会建议这样的事情:
const roll = dice => {
const [num, max] = dice.split('d');
let r = 0;
for (let i = 0; i < num; i++) {
r += Math.floor(Math.random() * max) + 1;
}
return r;
}
let output = input = 'I roll 1d3 and 2d4 and 1d3 also 1d8 and 1d8 dice';
const matches = input.match(/\d+d\d+/g);
const rolls = matches.map(dice => `${dice}=(${roll(dice)})`);
rolls.forEach(roll => {
const [dice] = roll.split('=');
output = output.replace(new RegExp(` ${dice} `), ` ${roll} `);
});
console.log('IN:', input)
console.log('OUT:', output);
添加回答
举报