code: public static String escapeJsString(String string, String quote) {
      // This should be expanded to match all invalid characters (e.g. newlines) but for the moment
      // we'll trust we'll only get quotes.
      Pattern escapePattern = Pattern.compile("([^\\\\])" + quote);
  
      // Prepend a space so that the regex can match quotes at the beginning of the string
      Matcher m = escapePattern.matcher(" " + string);
      StringBuffer sb = new StringBuffer();
  
      while (m.find()) {
        // $1 -> inserts the character before the quote \\\\\" -> \\", apparently just \" isn't
        // treated literally.
        m.appendReplacement(sb, "$1\\\\" + quote);
      }
  
      m.appendTail(sb);
  
      // Remove the prepended space.
      return sb.substring(1);
    }
docs: Escape characters for safe insertion in a JavaScript string.
  
  @param string the string to escape
  @param quote  the type of quote to escape. Either " or '
  @return the escaped string