Solid javascript encode uri - javascript

I've read this and more articles:
When are you supposed to use escape instead of encodeURI / encodeURIComponent?
Still I have not found a solid encode/decode uri solution.
Let's say I have these variables
var first = 'Hello&and';
var second = "Let's have cite";
var third = 'And "hash,.#$';
var fourth = 'åäö other strange chars';
An unencoded url would be:
var url 'http://example.com/?first=' + first + '&second=' + second + '&third=' + third + '&fourth=' + fourth;
Later it should be in an ajax request like:
xhr = new XMLHttpRequest();
xhr.open('POST', url );
I tried this:
var url 'http://example.com/?first=' + encodeURIComponent(first);
But it does not work with #. So what is a solid encoding solution for all characters?
I don't use jQuery, just javascript.

Use the encodeURIComponent when encoding uri parameters. When you encode a hashtag with that function it will result in the string "%23".
So in your example:
var first = 'Hello&and';
var second = "Let's have cite";
var third = 'And "hash,.#$';
var fourth = 'åäö other strange chars';
var url = 'http://example.com/?first=' + encodeURIComponent(first) + '&second=' + encodeURIComponent(second) + '&third=' + encodeURIComponent(third) + '&fourth=' + encodeURIComponent(fourth);
Will result in the url variable containing the string:
http://example.com/?first=Hello%26and&second=Let's%20have%20cite&third=And%20%22hash%2C.%23%24&fourth=%C3%A5%C3%A4%C3%B6%20other%20strange%20chars
More information of the encodeURIComponent function can be found here.
(citation from w3 school) This function encodes special characters. In
addition, it encodes the following characters: , / ? : # & = + $ #

You can try using escape() function. This has saved me many-a times.
escape('#') does yield %23.

Related

Should URLs be encoded with encodeURIComponent() or escape()?

I am trying to encode URL using encodeURIComponent method. Some parameters in URL also contain special characters (of ISO-8859-1 charset) like é, è, which are not correctly encoded.
For example éis encoded to %C3%A9 instead of %E9
As a alternative I have used escape method for encoding and it is working absolutely fine.
But it does not encode some characters like + - * / . _ #
I am in doubt whether i should use it or not and most of the articles say that escape() should be avoided. Can anyone please tell me how can I get the correct encoding using encodeURIComponent or should I use escape?
CODE: there is a function "get" in which request is sent and encodeFormularDatas is used to encode url parameters. HTML page encoding is ISO-8859-1.
this.get = function(url, answerTreatement, options) {
var request = this.newRequest();
var target = url;
if (options.parameters) {
target += "?"+this.encodeFormularDatas(options.parameters);
}
request.open("POST", target, true);
request.send(null);
}
this.encodeFormularDatas = function(values) {
var pairs = [];
var regexp = /%20/g; // encoded space
for (var name in values) {
var value = values[name];
var pair = encodeURIComponent(name).replace(regexp, "+") + '=' +
encodeURIComponent(value).replace(regexp, "+");
pairs.push(pair);
}
return pairs.join('&');
};

Trimming a string from the end in Javascript

In Javascript, how can I trim a string by a number of characters from the end, append another string, and re-append the initially cut-off string again?
In particular, I have filename.png and want to turn it into filename-thumbnail.png.
I am looking for something along the lines of:
var sImage = "filename.png";
var sAppend = "-thumbnail";
var sThumbnail = magicHere(sImage, sAppend);
You can use .slice, which accepts negative indexes:
function insert(str, sub, pos) {
return str.slice(0, pos) + sub + str.slice(pos);
// "filename" + "-thumbnail" + ".png"
}
Usage:
insert("filename.png", "-thumbnail", -4); // insert at 4th from end
Try using a regular expression (Good documentation can be found at https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions)
I haven't tested but try something like:
var re = /(.*)\.png$/;
var str = "filename.png";
var newstr = str.replace(re, "$1-thumbnail.png");
console.log(newstr);
I would use a regular expression to find the various parts of the filename and then rearrange and add strings as needed from there.
Something like this:
var file='filename.png';
var re1='((?:[a-z][a-z0-9_]*))';
var re2='.*?';
var re3='((?:[a-z][a-z0-9_]*))';
var p = new RegExp(re1+re2+re3,["i"]);
var m = p.exec(file);
if (m != null) {
var fileName=m[1];
var fileExtension=m[2];
}
That would give you your file's name in fileName and file's extension in fileExtension. From there you could append or prepend anything you want.
var newFile = fileName + '-thumbnail' + '.' + fileExtension;
Perhaps simpler than regular expressions, you could use lastindexof (see http://www.w3schools.com/jsref/jsref_lastindexof.asp) to find the file extension (look for the period - this allows for longer file extensions like .html), then use slice as suggested by pimvdb.
You could use a regular expression and do something like this:
var sImage = "filename.png";
var sAppend = "-thumbnail$1";
var rExtension = /(\.[\w\d]+)$/;
var sThumbnail = sImage.replace(rExtension, sAppend);
rExtension is a regular expression which looks for the extension, capturing it into $1. You'll see that $1 appears inside of sAppend, which means "put the extension here".
EDIT: This solution will work with any file extension of any length. See it in action here: http://jsfiddle.net/h4Qsv/

Get data from URL with Javascript RegExp

I have a consistent URL along the lines of: http://www.site.com/user/Ryan and I want to retreive the domain extension and the username, as to say: http://www.site.(*)/user/(*)
I have two options (afaik) split() or a regexp, split() doesn't really sound too stable (also since the extension could be 'com' or 'com.br', so I'll probably like to use the regexp option, but I have no idea how get started on this one..
var re = /http:\/\/www.site.([^\/]*)\/user\/(\w*)/
var tokens = 'http://www.site.com.br/user/Ryan'.match(re);
var theWholeUrl = tokens[0];
var domain = tokens[1];
var username = tokens[2];
alert('theWholeUrl: ' + theWholeUrl);
alert('domain: ' + domain);
alert('username: ' + username);

How to sanitize "+" sign in url before searching?

// Description: I try to search Wolframalpha.com with JS search
// but I get an odd action with "+" sign, apparently because "+" is
// not just to sum things. Here an example:
var query=1+2;
// WA interpretes "+" to "%2B" after the execution
// but when I try to replace "+" with "%2B"
// WA replaces "%2B" with %225B"
// So replacing this way may end up into some odd loop
//
// How should I replace "+"/sanitize correctly?
// Or am I do it the wrong way? How to search WA in JS?
query=query.replace("+","%2B");
var url = 'http://www.wolframalpha.com/input/?i=';
var searchUrl = url + escape(query);
window.open(searchUrl, form.target || "_blank");
escape isn't for URL-encoding. It does something similar, but different. You want encodeURIComponent (link). You also want quotes around your query var's value (first line below):
var query="1+2";
var url = 'http://www.wolframalpha.com/input/?i=';
var searchUrl = url + encodeURIComponent(query);
window.open(searchUrl, form.target || "_blank");
Live example
encodeURIComponent will encode the + correctly.
I think your issue is var query=1+2; it's not handling query as a string so replace is not a function that can be called on line query=query.replace("+","%2B");
It needs to be var query='1+2';

How to replace a space in a URL in JavaScript?

These are the 2 relevant lines from a function written in JavaScript:
var v_depttime = document.getElementById("EDDepttime").value ;
url = url+"?select_bno="+v_busno+"&select_depttime="+v_depttime ;
It sends the select_depttime as 2010-01-24 14:30:00
and I want it to be an URL encoded string like 2010-01-24%2014:30:00
How is it done in JavaScript?
Use encodeURI or encodeURIComponent.
Use encodeURIComponent:
url = url +
"?select_bno=" + encodeURIComponent(v_busno) +
"&select_depttime=" + encodeURIComponent(v_depttime);

Categories