0

In JavaScript I can uses a regex to replace tex:

var textSearch = "10";
var textReplace = "2";
var c = alayer.textItem.contents
 c = c.replace(new RegExp(textSearch, "g"),textReplace);
 alert(c);

text strings of "10" gets replaced with "2". Huzzah!

However, I was unable to do a global replace without a new RegExp constructor I got into a mess.

  c = c.replace(textSearch, textReplace); //2 10 10 

I tried various iterations of /g and "g" to no avail.

Do you have to uses regxEx in the form of new regExp() when using variables, or am I missing a trick? Reginald X. Pression where are you?? I need your help!

Ghoul Fool
  • 6,249
  • 10
  • 67
  • 125
  • Without using regex you cannot do **replace-all** – anubhava Mar 11 '15 at 14:20
  • Couldn't you do `c = c.replace(/10/g, 2);`? – j08691 Mar 11 '15 at 14:21
  • If you want to use `replace`, you can use a regex (global or not) or a string (not global). But you can use `split` and `join` instead. – Oriol Mar 11 '15 at 14:22
  • Who is Reginald X. Pression? – Oriol Mar 11 '15 at 14:22
  • @j08691 I gave that (well would of gave that) in an answer. But using `new RegExp()` is a better idea here since it's a variable. – Spencer Wieczorek Mar 11 '15 at 14:22
  • @anubhava Yes you can. Also using the `RegExp` object **is** using regex. – Spencer Wieczorek Mar 11 '15 at 14:26
  • @SpencerWieczorek: You probably didn't understand my comment. If you think it can be done without using any regex and looping across all platforms then post an answer below. – anubhava Mar 11 '15 at 14:27
  • @anubhava I cannot post an answer in questions marked as duplicates. Also I did understand your comment, but you don't appear to understand the OP's question. They are not asking how to do this without regexp but rather how to do it without using the RegExp object. – Spencer Wieczorek Mar 11 '15 at 14:29
  • I definitely understood the question. You cannot avoid `RegExp` when using value from a variable in regex. – anubhava Mar 11 '15 at 14:35

1 Answers1

1

Indeed, normally you have to use a RegExp to replace more than once instance. There is however a non-standard third "flags" argument to replace() that should achieve a global replace even if you use a plain string as the search expression: c = c.replace('needle', haystack, 'g'); See the MDN reference. Note though that this extra argument is not supported in e.g. Chrome, so the RegExp approach is the best.

Peter Herdenborg
  • 5,736
  • 1
  • 20
  • 21