How to send strings in the URL via JS or jQuery?

Asked

Viewed 3,107 times

5

How do I turn a string, ex: minha string in minha+string to send to the URL? Can be in JS or jQuery

3 answers

6


Stick to the pattern

The character encoding to send in a URL or in the body of a request is not so simple and may vary as the case may be. If the problem was only with the URL, a simple replacement would solve it, but there are patterns.

Use encodeURIComponent(), carefully

As Antonio Carlos said in the other answer, you must use the function encodeURIComponent().

However, as encodeURIComponent transforms all the special characters to the required format, some few symbols are ignored: !, ', (, ) and *.

Encoding the additional characters

To mozilla documentation gives an example of how to "fix" this and better adhere to the character specification (RFC 3986):

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

Coding spaces for application/x-www-form-urlencoded

Additionally, if you are making a request of type POST and the body coding format is application/x-www-form-urlencoded, then to suit the pattern you must still replace the coded spaces with %20 by the sum sign (+).

Example:

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

Use only in parameter values

Another important detail is that you cannot use encodeURIComponent in the whole URL, but should use for each parameter value. For example:

var url = '/destino?param=' + encodeURIComponent(valorParametro);

Or better yet, use a "corrected routine":

var url = '/destino?param=' + toFormUrlEncoded(valorParametro);
//ajax post 

Beware of encodeURI

To encode an entire URL, there is the function encodeURI. In theory, it should encode the ready-made URL instead of a parameter, but it does not encode control characters like ? and &.

So it’s not very reliable, because if you have something like param=eu & você will have problems routine has no way to differentiate a & as a legitimate parameter separator and as part of the value of a parameter.

5

Usually what is done to send a string through the URL is to use the function encodeURIComponent(), as in the example:

Code:

var uri = "http://w3schools.com/my test.asp?name=ståle&car=saab";
var res = encodeURIComponent(uri);

Upshot:

http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab

However, note that instead of + he puts the code %20 in place of space.

Another option is to use the function encodeURI(), who has similar effect, but does not replace: , / ? : @ & = + $ #.

Source: http://www.w3schools.com/jsref/jsref_encodeuricomponent.asp

4

In addition to what has already been answered by the other two responses, about the use of encodeURIComponent() to escape potentially harmful or disturbing characters I usually use functions to create a strng of an object with data to send.

For example:

function prepareData(data) {
    return Object.keys(data).map(function(key) {
        return [key, data[key]].join('=');
    }).join('&');
}

function parseURI(str) {
    var data = {};
    str.split('&').forEach(function(keyValue){
        var parts = keyValue.split('=');
        data[parts[0]] = parts[1];
    });
    return data;
}

the function prepareData converts objects into a query string, that is to say of {foo: 'bar'} in foo=bar. In the function the ? that starts the query string, I prefer to join it to the part.

The other does the opposite, used on the client side to read the query string of the URL, thus using:

var object = parseURI(location.search.slice(1));
  • 2

    No joke, your participation here on the site gave a book "Tricks and changes, top-down Javascript, by Sergio Crisostomo". Bloody ninja :)

  • 1

    @brasofilo :) My philosophy is "fake it Till you make it", all I know today I have been learning here, and with other communities. So I am happy to continue sharing.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.