5

In my app I need the code like:

string1.replaceAll(string2, myConstatntString)

Problem is that string1 and string2 can contain special symbols like '('.

I wish to quote string2 using java.util.regex.Pattern.quote(String arg):

string1.replaceAll(Pattern.quote(string2), myConstatntString);

But java.util.regex.Pattern is not available in GWT client side. Does GWT have any replacements for Pattern.quote?

MartinTeeVarga
  • 10,478
  • 12
  • 61
  • 98
A cup of tea
  • 404
  • 1
  • 4
  • 13

1 Answers1

3

I believe there isn't, because JavaScript doesn't have its own method. What you can do is to use String.replace() instead of String.replaceAll(), given that you don't need regexp at all. If you do, you will have to write your own method.

This is how it is done in JavaScript: Is there a RegExp.escape function in Javascript?

And this is how it is done in Java:

public static String quote(String s) {
    int slashEIndex = s.indexOf("\\E");
    if (slashEIndex == -1)
        return "\\Q" + s + "\\E";

    StringBuilder sb = new StringBuilder(s.length() * 2);
    sb.append("\\Q");
    slashEIndex = 0;
    int current = 0;
    while ((slashEIndex = s.indexOf("\\E", current)) != -1) {
        sb.append(s.substring(current, slashEIndex));
        current = slashEIndex + 2;
        sb.append("\\E\\\\E\\Q");
    }
    sb.append(s.substring(current, s.length()));
    sb.append("\\E");
    return sb.toString();
}

From: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/regex/Pattern.java

(the actual implementation in Java 1.5+)

Community
  • 1
  • 1
MartinTeeVarga
  • 10,478
  • 12
  • 61
  • 98
  • +1 i don't think there's one either. You could write a native method in GWT the calls the JS method. – Bohemian May 30 '13 at 04:34