Replace Specific Elements (unique Or Duplicates) From A String In Js
My code automatically search the string for /d+d/d+ elements (roll dices) and adds random number suffixes and stores them as elements in an array. I want to create a new string w
Solution 1:
Using only the two items you provide as input (the string and the array with ndn=(n)
kind of words), you can proceed as follows:
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);
It is assumed that the array is well-formed, i.e. that indeed those items were derived correctly from the string and all the string-parts before the equal sign (like "1d3") occur in the string.
Note that strings are immutable, so you cannot really mutate a string. The only way is to create a new string and assign it back to the same variable. But that is not mutation; that is assignment of a new string.
Solution 2:
If I understood your requirements, I think your solution is overcomplicated. I'd suggest something like this:
constroll = 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(newRegExp(` ${dice} `), ` ${roll} `);
});
console.log('IN:', input)
console.log('OUT:', output);
Post a Comment for "Replace Specific Elements (unique Or Duplicates) From A String In Js"