Replace specific elements (unique or duplicates) from a string in JS

强颜欢笑 提交于 2019-12-11 10:56:25

问题


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 with the new modified elements of my array.

(I don't want to split string in Array, replace the same elements with the other array in a brand new one and then join it to a string. I need to modify it and save it in a new string)

Example:

String changes through user input so if i have:

str = ' I roll 1d3 and 2d4+3 and 1d3 also 1d8 and 1d8 dice ';

then mydice(str) finds all dice names and produces a new array like that:

array = [ "1d3:[2]=2" , "2d4:[1,2]+3=6" , "1d3:[1]=1", "1d8:[7]=7", "1d8:[5]=5"] ;

Desired Output:

str = ' I roll 1d3:[2]=2 and 2d4:[1,2]+3=6 and 1d3:[1]=1 also 1d8:[7]=7 and 1d8:[5]=5 '; 

回答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.




回答2:


If I understood your requirements, I think your solution is overcomplicated. I'd suggest something like this:

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);


来源:https://stackoverflow.com/questions/57360931/replace-specific-elements-unique-or-duplicates-from-a-string-in-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!