19

I'm looking for similar function as urlencode() from PHP just in JavaScript. jQuery library is allowed.

Basically, I need to encode the string and then redirect the user to another page just with JavaScript.

6 Answers 6

29

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

Sign up to request clarification or add additional context in comments.

Comments

4

From: https://www.php.net/manual/en/function.urlencode.php

Returns a string in which all non-alphanumeric characters except -_. have been replaced with a percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs. It is encoded the same way that the posted data from a WWW form is encoded, that is the same way as in application/x-www-form-urlencoded media type. This differs from the » RFC 3986 encoding (see rawurlencode()) in that for historical reasons, spaces are encoded as plus (+) signs

From: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent:

encodeURIComponent() escapes all characters except:
Not Escaped: A-Z a-z 0-9 - _ . ! ~ * ' ( )

A snippet is provided near the bottom of that page which looks like this:

function fixedEncodeURIComponent(str) {
  return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
    return '%' + c.charCodeAt(0).toString(16);
  });
}

I am slightly adjusting the provided javascript snippet to include a couple more characters.

My Code:

function urlEncodeLikePHP(str) {
    return encodeURIComponent(str).replace(/[.!~*'()]/g, function(c) {
        return '%' + c.charCodeAt(0).toString(16);
    });
}

Usage:

urlEncodeLikePHP("._!_~_*_'_(_)-\\-&-|-/");
// effectively: "._!_~_*_'_(_)-\-&-|-/"

Encoded Output:

%2e_%21_%7e_%2a_%27_%28_%29-%5C-%26-%7C

Comments

4

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;
}

JS function equivalent to PHP's urldecode.

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

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

    if (c === '+') {
      newStr += ' ';
    }
    else if (c === '%') {
      const hex = str.substr(i + 1, 2);
      const code = parseInt(hex, 16);
      newStr += String.fromCharCode(code);
      i += 2;
    }
    else {
      newStr += c;
    }
  }

  return newStr;
}

2 Comments

I need this the way around, do you also have such a script?
Updated post with urldecode.
3

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).

Comments

0

encodeURIComponent()
http://www.w3schools.com/jsref/jsref_encodeURIComponent.asp

1 Comment

This is not the same. One example is that encodeURIComponent() does not encode parentheses.
0

Try urlencode from http://locutus.io/php/url/urlencode/. I've tested it in several cases I had and it worked.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.