1.2k questions

1.4k answers

361 comments

339 users

Categories

Sidebar
+2 votes
1.1K views
by mike-r-7535 (13.8k points)

Sometimes I have a script that calls replaceAll() on my string variable, but it only works some of the time.  Why would it only work some of the time?

1 Answer

+3 votes
 
Best answer

This is probably a Java String vs Javascript String problem.  Java Strings have a replaceAll() method, but Javascript Strings do not.

You can force/cast your string so it is a Javascript string and then do a global replace:

str = '' + str;
str.replace(/foo/g, "bar");


OR

You can force/cast your string so it is a Java String and then do a replaceAll:

str = new java.lang.String(str);
str.replaceAll("foo", "bar");
by mike-r-7535 (13.8k points)
selected by ron-s-6919
by mike-r-7535 (13.8k points)
It is worth mentioning that these methods above can use regular expressions.  If regular expressions are not needed, you can also use StringUtils.replace();
...