Jeff Noel
Jeff Noel

Reputation: 7618

Converting special characters (é è ë) using url encoding

I am making a function where user's email client just opens up with a pre-filled content (javascript).

The thing is that I am having trouble converting special characters so they are shown correctly into the email client (the content being passed by url).

I have written a function, but after doing a console.log() I found out that it won't even convert characters (probably because I'm trying to replace a char with a string).

function url_encode(item)
{
    for (i in item)
    {
        a = item[i]
        switch (a)
        {
            case "À": a='%C0';
            break;
            case "È": a='%C8';
            break;
            case "É": a='%C9';
            break;
            case "Ê": a='%CA';
            break;
            case "à": a='%E0';
            break;
            case "è": a='%E8';
            break;
            case "é": a='%E9';
            break;
            case "ê": a='%EA';
            break;
            case "ë": a='%EB';
            break;  
        }
        item[i] = a;
        console.log(item[i])
    }
    return item;
}

Anyone has found a successful way or has an idea (or a fix) why this is not working as intended?

Edit: encodeURI function does not support é and è characters (which are used a lot in French), those result as é and è.

Upvotes: 2

Views: 4843

Answers (1)

Šime Vidas
Šime Vidas

Reputation: 186013

Is this OK?

var url_encode = function ( url ) {
    return url.split( '' ).map(function ( c ) {
        return /[ÀÈÉÊàèéêë]/.test( c ) ? '%' + c.charCodeAt( 0 ).toString( 16 ).toUpperCase() : c;
    }).join( '' );
};

Live demo: http://jsfiddle.net/v2He6/

(Note: You would need to polyfill .map() for IE8.)

Example:

url_encode( 'ABCÀDEFè' ) // "ABC%C0DEF%E8"

Upvotes: 6

Related Questions