Sidebar

Why doesn't my String have a replaceAll() function?

+2 votes
904 views
asked Jul 3, 2013 by mike-r-7535 (13,830 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");
answered Jul 3, 2013 by mike-r-7535 (13,830 points)
selected Jul 3, 2013 by ron-s-6919
commented Mar 23, 2017 by mike-r-7535 (13,830 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();
...