0

I am trying to replace a variety of strings (tokens) in a textarea using jquery replace(). I can make it work except it only replaces the first occurrence in the textarea and need it to do all.

I'm able to do the replacements like this;

var token = '{IP}';

sdText = sdText.replace(token, $('.' + data.name).val());

I'm needing to do this instead to catch all occurrences;

var token = '{IP}';

sdText = sdText.replace(/token/g, $('.' + data.name).val());

because there may be multiple occurrences of the token in the textarea I need replaced. The value of token changes per each iteration of an .each() loop, I need that value injected into the regex statement for each iteration.

Does anyone know how I would accomplish this?

Thanks

Skittles
  • 2,866
  • 9
  • 31
  • 37

1 Answers1

1

For dynamic regex use RegExp() constructor.

var regex = new RegExp(token, 'g');

sdText = sdText.replace(regex, $('.' + data.name).val());
Tushar
  • 85,780
  • 21
  • 159
  • 179