urlencode() from PHP in JavaScript?

My code is the JS function equivalent to PHP's urlencode (based on PHP's source code).

function urlencode(str) {
  let newStr = '';
  const len = str.length;

  for (let i = 0; i < len; i++) {
    let c = str.charAt(i);
    let code = str.charCodeAt(i);

    // Spaces
    if (c === ' ') {
      newStr += '+';
    }
    // Non-alphanumeric characters except "-", "_", and "."
    else if ((code < 48 && code !== 45 && code !== 46) ||
             (code < 65 && code > 57) ||
             (code > 90 && code < 97 && code !== 95) ||
             (code > 122)) {
      newStr += '%' + code.toString(16);
    }
    // Alphanumeric characters
    else {
      newStr += c;
    }
  }

  return newStr;
}

Have a look at phpjs.org if you're searching for a JS function equivalent to PHP:

http://phpjs.org/functions/urlencode:573

Here you can use encodeURIComponent() (with some modifications).


There is no function quite matching urlencode(), but there is one quite equivalent to rawurlencode(): encodeURIComponent().

Usage: var encoded = encodeURIComponent(str);

You can find a reference here:

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/encodeURIComponent