0

in google script I am trying to replace a %string basing on the character following it.

I've tried using:

var indexOfPercent = newString.indexOf("%"); 

and then check the character of indexOfPercent+1, but indexOf returns only the first occurrence of '%'.

How can I get all occurrences? Maybe there is easier way to do that (regular expressions)?


EDIT:

Finally I want to replace all my % occurrences to %%, but not if percent sign was part of %@ or %@.

To sum up: my string: Test%@ Test2%s Test3%. should look like: Test%@ Test2%s Test3%%.

I've tried using something like this:

  //?!n Matches any string that is not followed by a specific string n
  //(x|y)   Find any of the alternatives specified
  var newString = newString.replace(\%?![s]|\%?![%], "%%")

but it didn't find any strings. I am not familiar with regex's, so maybe it is a simple mistake.

Thanks

Max Makhrov
  • 17,309
  • 5
  • 55
  • 81
izik461
  • 1,131
  • 12
  • 32

1 Answers1

1

Try this code:

// replace all '%'
var StrPercent = '%100%ffff%';
var StrNoPersent = StrPercent.replace(/\%/g,'');
Logger.log(StrNoPersent); // 100ffff

Look for more info here


Edit

In your case you need RegEx with the character not followed by group of characters. Similiar question was asked here:

Regular expressions - how to match the character '<' not followed by ('a' or 'em' or 'strong')?

Thy this code:

function RegexNotFollowedBy() {

var sample = ['Test%@',
              'Test2%s',
              'Test3%',
              '%Test4%'];

var RegEx = /%(?!s|@)/g;
var Replace = "%%";

var str, newStr;

  for (var i = 0; i < sample.length; i++) {
      str = sample[i];
      newStr = str.replace(RegEx, Replace);
      Logger.log(newStr);

  }

}

I'll explain expression /%(?!s|@)/g:

  • % -- look '%'
  • (text1|text2|text3...|textN) -- not followed by text1, 2 etc.
  • g -- look for any accurance of searched text
Community
  • 1
  • 1
Max Makhrov
  • 17,309
  • 5
  • 55
  • 81