OAuth safe encodeURIComponent of string
handles ignored characters that OAuth expects encoded "! * ' ( )"
508137
function uriEncodeString( text ){
    return encodeURIComponent(text).replace( /[\!\*\'\(\)]/g, function( chr ){
        chr = chr.charCodeAt(0).toString(16);
        while( chr.length < 2 ){
            chr = '0'+hex;
        }
        return '%'+chr;
    } )
}
546354
private static void encodeURIQuery(Writer writer, final String string, int offset, final String characterEncoding)
            throws IOException
    {
        //StringBuilder sb = null;    //create later on demand
        int start = offset;
        int length = string.length();
        int realLength = length-offset;
        String app;
        char c;
        //boolean endLoop = false;
        for (int i = offset; i < length; ++i)
        {
            app = null;
            c = string.charAt(i);
            
            // - From %00 to %20 (' ' %20 could encode as +, but %20 also works, so we keep %20)
            // - <"> %22 (If there is encode of "%", there is a risk of duplicate encoding, so 
            //            we make easier and omit this one)
            // - "<" %3C, ">" %3E,
            // - "\" %5C, "^" %5E, "`" %60 
            // - "{" %7B, "|" %7C, "}" %7D
            // - From %7F ad infinitum (each character as many bytes as necessary but take into account
            //   that a single char should contain 2,3 or more bytes!. This data should be encoded 
            //   translating from the document character encoding to percent encoding)
            //
            // "&" should be encoded as "&amp;" because this link is inside an html page, and 
            // put & is invalid in this context   
            
            if (   (c <= (char)0x20) || (c >= (char)0x7F) || 
                    c == '"' || c == '<' ||
                    c == '>' || c == '\\' || c == '^' || c == '`' ||
                    c == '{' || c == '|' || c == '}')
            {
                // The percent encoding on this part should be done using UTF-8 charset
                // as RFC 3986 Section 3.2.2 says
                //app = percentEncode(c, characterEncoding);
                if (start < i)
                {
                    writer.write(string, start, i-start);
                }
                start = i+1;
                percentEncode(writer, c, characterEncoding);
            }
            else if (c == '%')
            {
                if (i + 2 < length)
                {
                    char c1 = string.charAt(i+1);
                    char c2 = string.charAt(i+2);
                    if ((( c1 >= '0' && c1 <='9') || (c1 >='A' && c1 <='Z') || (c1 >='a' && c1 <='z')) &&
                        (( c2 >= '0' && c2 <='9') || (c2 >='A' && c2 <='Z') || (c2 >='a' && c2 <='z')))
                    {
                        // do not percent encode, because it could be already encoded
                    }
                    else
                    {
                        //app = percentEncode(c, characterEncoding);
                        if (start < i)
                        {
                            writer.write(string, start, i-start);
                        }
                        start = i+1;
                        percentEncode(writer, c, characterEncoding);
                    }
                }
                else
                {
                    //app = percentEncode(c, characterEncoding);
                    if (start < i)
                    {
                        writer.write(string, start, i-start);
                    }
                    start = i+1;
                    percentEncode(writer, c, characterEncoding);
                }
            }
            else if (c == '&')
            {
                if (i+4 < length )
                {
                    if ('a' == string.charAt(i+1) &&
                        'm' == string.charAt(i+2) &&
                        'p' == string.charAt(i+3) &&
                        ';' == string.charAt(i+4))
                    {
                        //Skip
                    }
                    else
                    {
                        app = "&amp;";
                    }
                }
                else
                {
                    app = "&amp;";
                }
            }
            else
            {
                //No encoding, just do nothing, char will be added later.
            }
                        
            if (app != null)
            {
                //if (sb == null)
                //{
                //    sb = new StringBuilder(string.substring(0, i));
                //}
                //sb.append(app);
                if (start < i)
                {
                    writer.write(string, start, i-start);
                }
                start = i+1;
                writer.write(app);
            }
            //else
            //{
            //    if (sb != null)
            //    {
            //        sb.append(c);
            //    }
            //}
            //if (endLoop)
            //{
            //    break;
            //}
        }
        
        //if (sb == null)
        //{
        //    return string;
        //}
        //else
        //{
        //    return sb.toString();
        //}
        if (start == offset)
        {
            writer.write(string, offset, realLength);
        }
        else if (start < length)
        {
            writer.write(string,start,length-start);
        }
    }
123265
function encodeURIParams(params, prefix) {
    let parts = [];
    for (const name in params) {
        if (Object.prototype.hasOwnProperty.call(params, name)) {
            const paramName = prefix ? (`${prefix}[${encodeURIComponent(name)}]`) : encodeURIComponent(name);
            if (typeof params[name] === 'object') {
                parts = Array.prototype.concat.apply(parts,
                    encodeURIParams(params[name], paramName));
            } else {
                parts.push(`${paramName}=${encodeURIComponent(params[name])}`);
            }
        }
    }
    return parts;
}
403658
private String encodeUri( String uri )
    {
        String newUri = "";
        StringTokenizer st = new StringTokenizer( uri, "/ ", true );
        while ( st.hasMoreTokens())
        {
            String tok = st.nextToken();
            if ( tok.equals( "/" ))
                newUri += "/";
            else if ( tok.equals( " " ))
                newUri += "%20";
            else
            {
                newUri += URLEncoder.encode( tok );
                // For Java 1.4 you'll want to use this instead:
                // try { newUri += URLEncoder.encode( tok, "UTF-8" ); } catch ( java.io.UnsupportedEncodingException uee ) {}
            }
        }
        return newUri;
    }
1055656
function (data) {
    var str = '', start = true;
    var jsondata = '';
    for (var key in data) {
      if (typeof (jsondata = JSON.stringify(data[key])) === 'string') {
        str += (start? '': '&');
        str += encodeURIComponent(key) + '=' + encodeURIComponent(jsondata);
        if (start) { start = false; }
      }
    }
    return str;
  }
945256
function uriEncodeParams( obj ){
    var pairs = [], key;
    for( key in obj ){
        pairs.push( uriEncodeString(key) +'='+ uriEncodeString(obj[key]) );
    }
    return pairs.join('&');
}
785494
function(value) {
		if ([
			['%5B', '%5D'],
			['%7B', '%7D']
		].some(function isencoded(tokens) {
			return value.startsWith(tokens[0]) && value.endsWith(tokens[1]);
		})) {
			try {
				value = JSON.parse(decodeURIComponent(value));
			} catch (exception) {
				value = null;
				console.error(this + ': Bad JSON: ' + exception.message);
			}
		}
		return value;
	}
86406
function encodeEntities(value) {
  return value.
    replace(/&/g, '&amp;').
    replace(SURROGATE_PAIR_REGEXP, function (value) {
      var hi = value.charCodeAt(0);
      var low = value.charCodeAt(1);
      return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';';
    }).
    replace(NON_ALPHANUMERIC_REGEXP, function (value) {
      return '&#' + value.charCodeAt(0) + ';';
    }).
    replace(/</g, '&lt;').
    replace(/>/g, '&gt;');
}
90747
private static String encodeHTMLEntities(String string) {
		if (string == null) {
			return null;
		}
		try {
			return URLEncoder.encode(string, Charset.defaultCharset().displayName());
		} catch (UnsupportedEncodingException exception) {
			return string;
		}
	}
625106
function _convertUnicode(originalStr) {
  let m;
  let c;
  let cStr;
  let lastI = 0;

  // Matches \u#### but not \\u####
  const unicodeRegex = /\\u[0-9a-fA-F]{4}/g;

  let convertedStr = '';
  while ((m = unicodeRegex.exec(originalStr))) {
    // Don't convert if the backslash itself is escaped
    if (originalStr[m.index - 1] === '\\') {
      continue;
    }

    try {
      cStr = m[0].slice(2); // Trim off start
      c = String.fromCharCode(parseInt(cStr, 16));
      if (c === '"') {
        // Escape it if it's double quotes
        c = `\\${c}`;
      }

      // + 1 to account for first matched (non-backslash) character
      convertedStr += originalStr.slice(lastI, m.index) + c;
      lastI = m.index + m[0].length;
    } catch (err) {
      // Some reason we couldn't convert a char. Should never actually happen
      console.warn('Failed to convert unicode char', m[0], err);
    }
  }

  // Finally, add the rest of the string to the end.
  convertedStr += originalStr.slice(lastI, originalStr.length);

  return convertedStr;
}
630737
function encodeProblemUrlChars(url) {
            if (!url)
                return "";

            var len = url.length;

            return url.replace(_problemUrlChars, function (match, offset) {
                if (match == "~D") // escape for dollar
                    return "%24";
                if (match == ":") {
                    if (offset == len - 1 || /[0-9\/]/.test(url.charAt(offset + 1)))
                        return ":"
                }
                return "%" + match.charCodeAt(0).toString(16);
            });
        }
677713
function (sep) {
            var nonEncodedSep = [];
            for (var i = 0, len = sep.length; i < len; i++) {
                if (sep[i] == encodeURIComponent(sep[i])) {
                    nonEncodedSep.push(sep[i]);
                }
            }
            return nonEncodedSep;
        }
1316450
function urlEncoded(gw, callback){
  var buffer = '';
  var readlength = 0;
  var $error = false;
  gw.req.on('data', function (chunk) {
    if (readlength > gw.content.length) {$error = true;}
    if (!$error) {
      readlength += chunk.length;
      buffer += chunk.toString('ascii');
    }
  });
  gw.req.on('end', function () {
    if ($error) {
      gw.error(400);
    } else {
      var params = gw.constructor.queryHeap(querystring.parse(buffer, '&', '='));
      gw.content.params = params;
      for(var i=0,k=Object.keys(params),l=k.length;i<l;i++){
        gw.params[k[i]]=params[k[i]];
      }
      callback();
    }
  });
}
1298515
private static final String urlEncode(String s) {
        try {
            return URLEncoder.encode(s, "UTF-8");
        } catch (Exception e) {
            logger.warn("Failed to encode '" + s + "'", e);
            return s;
        }
    }
773039
function encode(uri) {
    
    var prefix,
        protocolCode,
        encoded;

    // check each protocol, unless we've found a match
    // "urn:" is the one exception where we need to keep checking
    // slice so we don't check ""
    protocols.slice(1).forEach(function(protocol) {                        
        if ((!prefix || prefix === "urn:") && uri.indexOf(protocol) === 0) { 
            prefix = protocol;
        }
    });

    if (!prefix) {
        prefix = "";
    }
    
    encoded = util.stringToBytes(uri.slice(prefix.length));
    protocolCode = protocols.indexOf(prefix);    
    // prepend protocol code
    encoded.unshift(protocolCode);
    
    return encoded; 
}
172256
function (params, noEncode) {
      if(this.isObject(params)){

        var paramsStr = [];

        for (var key in params) {
          if (params.hasOwnProperty(key) && params[key] !== undefined) {
            var value = this.isObject(params[key])? this.buildParams(params[key], true) : params[key];
            paramsStr.push((noEncode? key : encodeURIComponent(key)) +
              '=' + (noEncode? this.escapeSpecials(value) : encodeURIComponent(value)));
          }
        }

        // Build string from the array.
        return paramsStr.join('&');

      } else {
        return params;
      }
    }
604475
private String encodeCharAtIndex(final String string, final int index, final State state) {
        final char c = string.charAt(index);

        /* Special-case: spaces are "%20" when not within query string, or when doing strict mode */
        if ((SPACE.matches(c) && ((state != State.QUERY && state != State.QUERY_PARAM) || strict)) ||
            (strict && PLUS.matches(c) && state == State.QUERY)) {
            return "%20";
        }

        /* Check if there are two hex digits after a percent */
        if (ESCAPED.matches(c) && string.length() > index + 2 &&
            HEX.matches(string.charAt(index + 1)) && HEX.matches(string.charAt(index + 2))) {
            return null;
        }
        
        /* We got this far - so if we are an illegal character, escape it */
        if (isIllegal(c, state)) {
            try {
                /* Special-case: asterisks are not encoded by URLEncoder.encode */
                if (c == '*') {
                    return "%2A";
                } else {
                    return URLEncoder.encode(Character.toString(c), "UTF-8");
                }
            } catch (UnsupportedEncodingException e) {
                throw new AssertionError("UTF-8 always exists, " + e.getMessage());
            }
        }
        
        /* Not illegal - so return null */
        return null;
    }