Problem with .replace method

Hi all,

I’m trying to use the “.replace” method into a string but only the first occurrence is replaced(smart client,developer)

Here an example:
[attachment=0]test_lettersTemplate.servoy[/attachment]

regards

Marco

I haven’t looked at your solution, but you probably have to use the “g” flag in your regular expression. g for global:

yourString.replace(/bla/g, "replacement");

Sorry Joas I don’t understand your answer. :(

I’m using 3 local string variable : “phrase1” “replacement” “phrase2”
Where into the “phrase1” I have my string template,into “replacement” I have the name of the user and “phrase2” is an empty string.

I do only:

phrase2 = phrase1.replace("##mySpecialTag##",replacement) 

Can you explain by using this example what I have to fix to make it work please?

In your example you put the text to be replaced between quotation marks. This should in fact be a regular expression that should be put between two slashes (/regexp/), not a string as in your example. Moreover, if you don’t add the “g” flag after the closing slash, the replace function will work only on the first occurrence of the pattern to be replaced. The replacement pattern must always be a string or a variable containing a string.

In my opinion, if you need to replace a variable your code should be something like this

var myVar = mySpecialTag;
var myregExp = new RegExp(myVar,"g");
phrase2 = phrase1.replace(myregExp,"replacement string");

If you used a string as replace pattern instead of a variable you should try this (where mySpecialTag must be a string constructed as a a regular expression)

phrase2 = phrase1.replace(/mySpecialTag/g,"replacement string");

Please note the “g” flag used as the second argument in the RegExp object construction or after the closing slash in the second example. This tells the replace function to check all the occurrences of the replace pattern

For a little more information about regular expressions in javascript, here is an easy tutorial.

Joas and Rioba,thanks to both for your time and for your help.

Now the concept is clear,and all works fine. :)

Marco

For simple replaces, you might also be interested in trying out

phrase2 = utils.stringReplace(phrase1, "##mySpecialTag##', replacement)

thanks jgarfield!