ctilley79
ctilley79

Reputation: 2195

Typescript/Javascript: Replace All String Occurrences with Random Number

I have the following function that replaces a string occurence with a random number. What I have currently replaces the string with the same random number. I need a function that replaces each instance a unique number. Here's what I have.

Attempt to Clarify:

I want to find all occurrences of '},{ and replace it with },"random":{ where random is a unique integer for each occurrence.

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

Currently the result is something to the effect of

},"1340":{"expense_category_id":"63","amount":3},"1340":{"expense_category_id":"62","amount":3}}}}

1340 should not have duplicated

Edit: The value of result before replace all is:

},{"expense_category_id":"63","amount":3},{"expense_category_id":"62","amount":3}}}}

Upvotes: 3

Views: 6942

Answers (2)

Daryl
Daryl

Reputation: 18895

Your replace call is wrong. You're passing in a string, you should be passing in a function that creates the number, not the result of the number itself.

    let result = "{A},{B},{C}";
    result = replaceAll(result, '},{', () => { return `},"${this.getRandomInt(1, 2000)}":{` });
    console.log(result);
    
    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");
    }

Upvotes: 1

DontVoteMeDown
DontVoteMeDown

Reputation: 21465

Pass a function to the replace() second parameter like this:

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

I'm not sure why, but it seems that it uses the same string generated for the first iteration for subsequent iterations. With a function, you force it to run everytime.

Upvotes: 7

Related Questions