How to replace a space in a URL in JavaScript? - 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);

Related

Javascript. How to extract URI encoded email from string?

var string = 'https://opt.portal.co.uk/index/stepregistration/Username/test%40test.es/nextstep/1/lang/es?kmi=K54Nv1RdlV71hhiLEdPg0UZ0%3D&_ga=1.217245974.18890806.1485212';
Email is encoded like so test%40test.es
What is the way to get this email address with JavaScript (no jQuery)?
You could accomplish this using the following way :
use decodeURIComponent() to decode the URI
use a regex to extract the email address
var string = 'https://opt.portal.co.uk/index/stepregistration/Username/test%40test.es/nextstep/1/lang/es?kmi=K54Nv1RdlV71hhiLEdPg0UZ0%3D&_ga=1.217245974.18890806.1485212';
var email = decodeURIComponent(string).match(/\w+#\w+\.\w+/g)[0];
console.log(email);
decodeURIComponent(string)
example from w3c:
var uri = "https://w3schools.com/my test.asp?name=ståle&car=saab";
var uri_enc = encodeURIComponent(uri);
var uri_dec = decodeURIComponent(uri_enc);
var res = uri_enc + "<br>" + uri_dec;
https://www.w3schools.com/jsref/jsref_decodeuricomponent.asp
In your example you'll want to extract the username from the url. Querystring or Hash key/value pairs might be easier to deal with but you can use a regular expression or split the url by '/' and loop the result to find the element after the 'Username' element.

How to get first two URL path segments?

How to get first two parts of the URL using AngularJS?
For example, I would like to get the two first path of this URL (as admin/password/):
http://localhost:3000/admin/password/57045b10eba5ca1dfd01a8fc4adb4f6c4efc6454b9454514
split the url on "/"
url = window.location.href.split("/")
now you have each word in a sepperate array item, then you can combine them into one string like
console.log(url[0] + url[1] + url[2]);
From Angular $location service:
url([url]);
Return URL when called without any parameter.
Use it like this:
$scope.currentUrl = $location.url();
If you don't need the whole URL, just split it.
You can use URL to get the pathname, then split on / and take the 2 segments you want:
var url = "http://localhost:3000/admin/password/57045b10eba5ca1dfd01a8fc4adb4f6c4efc6454b9454514";
var pathParts = new URL(url).pathname.split('/'); //["", "admin", "password", "57045b10eba5ca1dfd01a8fc4adb4f6c4efc6454b9454514"]
pathParts.slice(1, 3).join('/') + '/'; //"admin/password/"
You can do it using RegExp.
var str = 'http://localhost:3000/admin/password/57045b10eba5ca1dfd01a8fc4adb4f6c4efc6454b9454514';
var reg = str.match(/(?!:\d+)(\/\w+)(\/\w+)/g);
console.log(reg.toString().split('/').slice(1));

Solid javascript encode uri

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.

Can I do string formatting in Javascript? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
JavaScript equivalent to printf/string.format
I am creating code like this:
var ds = "ds=" + encodeURIComponent($('#DataSource').val());
var ex = "ex=" + encodeURIComponent($('#EID').val());
var to = "to=" + encodeURIComponent($('#TID').val());
var st = "st=" + encodeURIComponent($('#SID').val());
window.location.href = '/person?' + ds + "&" + ex + "&" + to + "&" + st;
Is there some way in Javascript that I could use formatting to make the code look a bit cleaner? Also do I need to encode each element or can I just encode the variable abc?
There's not a lot you can do, really. You could alias the encodeURIComponent method and use an array with join() if you're looking for something a little neater:
var e = encodeURIComponent,
arr = [
"ds=" + e($('#DataSource').val()),
"ex=" + e($('#EID').val()),
"to=" + e($('#TID').val()),
"st=" + e($('#SID').val())
];
window.location.href = '/person?' + arr.join("&");
Use <form> and put your input tags in them and you can call $('formContainer').serialize();
Its better to use name-value pairs(query strings), while sending data to URI. provide names as id to all of the input tags that you wish to capture. You will get something like:
/person/DataSource=ds&EID=ex&TID=to&SID=st
-HTH
Why don't you just write:
window.location.href = encodeURIComponent('/person?' +
$('#DataSource').val() + "&"
+ $('#EID').val() + "&" + $('#TID').val() + "&"
+ $('#SID').val());
Take a look at sprintf()
Also this can help: JavaScript equivalent to printf/string.format
var str = "/person?ds=%x&ex=%x&to=%x&st=%x";
var tokens = [
$("#DataSource").val(),
$("#EID").val(),
$("#TID").val(),
$("#SID").val()
];
tokens.forEach(function (token) {
str = str.replace("%x", encodeURIComponent(token));
});
location.href = str;
This will absolutely fall over if you have %x in your token string.
If you want a more generic solution try underscore.string

Replacing part of a string with javascript?

Let's say I have a URL that looks something like this:
http://www.mywebsite.com/param1:set1/param2:set2/param3:set3/
I've made it a varaible in my javascript but now I want to change "param2:set2" to be "param2:set5" or whatever. How do I grab that part of the string and change it?
One thing to note is where "param2..." is in the string can change as well as the number of characters after the ":". I know I can use substring to get part of the string from the front but I'm not sure how to grab it from the end or anywhere in the middle.
How about this?
>>> var url = 'http://www.mywebsite.com/param1:set1/param2:set2/param3:set3/';
>>> url.replace(/param2:[^/]+/i, 'param2:set5');
"http://www.mywebsite.com/param1:set1/param2:set5/param3:set3/"
Use regular expressions ;)
url.replace(/param2:([\d\w])+/, 'param2:new_string')
var key = "param2";
var newKey = "paramX";
var newValue = "valueX";
var oldURL = "http://www.mywebsite.com/param1:set1/param2:set2/param3:set3/";
var newURL = oldURL.replace( new RegExp( key + ":[^/]+" ), newKey + ":" + newValue);
You can pass regular expressions to the match() and replace() functions in javascript.

Categories