urlencode_smart

Smart url encodes characters without already urlencoded strings. You can also set allowed_chars in argument where default are "-_.~".

Created by: Raptiler
Installed 1 times

Category: Convert

Created on: Wednesday, October 30, 2024 at 11:34:41 AM

Updated on: Wednesday, November 20, 2024 at 5:32:24 PM

Tag arguments
[
   {
      "type": "string",
      "name": "allowed_chars",
      "help": "Characters that are allowed without encoding",
      "defaultValue": "-_.~"
   }
]
Code
class urlencode_smart {
  encode(input, { allowed_chars = "-_.~" }) {
    let result = "";
    let i = 0;

    while (i < input.length) {
      let char = input[i];

      if (char === "%" && i + 2 < input.length) {
        let next_two = input.slice(i + 1, i + 3);
        if (/[0-9A-Fa-f]{2}/.test(next_two)) {
          result += "%" + next_two;
          i += 3;
          continue;
        }
        result += "%25";
      } else {
        let char_code = char.charCodeAt(0);
        if (
          (char_code >= 48 && char_code <= 57) || // 0-9
          (char_code >= 65 && char_code <= 90) || // A-Z
          (char_code >= 97 && char_code <= 122) || // a-z
          allowed_chars.includes(char)
        ) {
          result += char;
        } else {
          let hex_value = char_code.toString(16).toUpperCase();
          result +=
            "%" + (hex_value.length === 1 ? "0" + hex_value : hex_value);
        }
      }

      i += 1;
    }

    return result;
  }
}