Search code examples
javascriptreplaceduplicatesunique

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

Solution

  • 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.