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

0

1 Answer 1

1

For dynamic regex use RegExp() constructor.

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

sdText = sdText.replace(regex, $('.' + data.name).val());
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.