Javascript. How to extract URI encoded email from string? - javascript

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.

Related

Access params in URL in JS (React)

I have this URL : http://localhost:3000/#access_token=90kzif5gr8plhtl9286sc1z1qbgoj3&scope=moderation%3Aread&token_type=bearer
and I want to get from this only the access_token value 90kzif5gr8plhtl9286sc1z1qbgoj3
How can I do it in Javascript please ?
Here is the solution:
const url = "http://localhost:3000/#access_token=90kzif5gr8plhtl9286sc1z1qbgoj3&scope=moderation%3Aread&token_type=bearer";
const hash = url.substring(url.indexOf('#') + 1);
let result = hash.split('&')
result = result[0].split('=')
console.log(result[1]); // "90kzif5gr8plhtl9286sc1z1qbgoj3"
Happy coding :)
As you can see in this the simplest way is :
var url_string = "http://localhost:3000/#access_token=90kzif5gr8plhtl9286sc1z1qbgoj3&scope=moderation%3Aread&token_type=bearer";
var url = new URL(url_string);
var c = url.searchParams.get("access_token");
You can try this by splitting the URL string into three strings and using the access token directly then
var url=http://localhost:3000/#access_token=90kzif5gr8plhtl9286sc1z1qbgoj3&scope=moderation%3Aread&token_type=bearer
var firstHalf=url.split('#access_token=')[1];
var required_token=firstHalf.split("&scope")[0];
print the value of required_token.
Required result will be "90kzif5gr8plhtl9286sc1z1qbgoj3"
your text is the string contained in window.location.hash, and a string of that format can be easily turned into a properly decoded key/value store using the URLSearchParams constructor:
const token = new URLSearchParams(window.location.hash).get("access_token");

Javascript how to remove parameter from URL sting by value?

How to remove parameters with value = 3 from URL string?
Example URL string:
https://www.example.com/test/index.html?param1=4&param2=3&param3=2&param4=1&param5=3
If you are targeting browsers that support URL and URLSearchParams you can loop over the URL's searchParams object, check each parameter's value, and delete() as necessary. Finally using URL's href property to get the final url.
var url = new URL(`https://www.example.com/test/index.html?param1=4&param2=3&param3=2&param4=1&param5=3`)
//need a clone of the searchParams
//otherwise looping while iterating over
//it will cause problems
var params = new URLSearchParams(url.searchParams.toString());
for(let param of params){
if(param[1]==3){
url.searchParams.delete(param[0]);
}
}
console.log(url.href)
There is a way to do this with a single regex, using some magic, but I believe that would require using lookbehinds, which most JavaScript regex engines mostly don't yet support. As an alternative, we can try splitting the query string, then just examining each component to see if the value be 3. If so, then we remove that query parameter.
var url = "https://www.example.com/test/index.html?param1=4&param2=3&param3=2&param4=1&param5=3";
var parts = url.split(/\?/);
var params = parts[1].replace(/^.*\?/, "").split(/&/);
var param_out = "";
params.forEach(function(x){
if (!/.*=3$/.test(x))
param_out += x;
});
url = parts[0] + (param_out !== "" ? "?" + param_out : "");
console.log(url);
You could use a regular expression replace. Split off the query string and then .replace &s (or the initial ^) up until =3s:
const str = 'https://www.example.com/test/index.html?param1=4&param2=3&param3=2&param4=1&param5=3';
const [base, qs] = str.split('?');
const replacedQs = qs.replace(/(^|&)[^=]+=3\b/g, '');
const output = base + (replacedQs ? '?' + replacedQs : '');
console.log(output);

Trouble reading a query string in a Query String?

I have a URL in a query string value that is similar to this one:
example.com/?p1=a1&p2=a2
And I have a query sting on my website that takes the URL and redirects to a certain page. Like this:
mysite.com/?url=example.com/?p1=a1&p2=a2
But the query string is misinterpreted. How can I separate the query string in the value URL from the actual URL? I have tried encoding the question marks and ampersands, but the page is missing the content from the value URL.
EDIT:
This is how I get the URL, through a javascript:
function nameps(url) {
url = url.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + url + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if (results == null) return "";
else {
return results[1];
}
}
how does the url value get passed to the javascript? That is the place you should be url-encoding the whole URL, to make
example.com/?p1=a1&p2=a2
be inputted into the javascript on your site as
example.com%2F%3Fp1%3Da1%26p2%3Da2
You will need to adjust your regex in your javascript to deal with this change in format or alternatively use a javascript url decoding function such as decodeuri .
decodeURI()
such as on your site:
function nameps(url) {
url = decodeURI(url); ///new line decodes the previously encoded URL
url = url.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + url + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if (results == null) return "";
else {
return results[1];
}
}
This would also involve however you pass the url value to the function above, would have to include the line :
url = encodeURI(url);
In order to correctly encode and format the address given.
I wouldn't try to get too complicated with the query string. Instead of this:
mysite.com/?url=example.com/?p1=a1&p2=a2
I would do this:
mysite.com/?url=example.com&p1=a1&p2=a2
Then I would parse it up and rebuild the secondary url from the components.
Trying to pack a query string in a query string is asking for trouble. I wouldn't waste any time trying to get it to work that way.

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 do I remove part of a string from a url using JQuery?

How do I remove everything before /post in this string below and add my own address using Javascript/JQuery
showLogo=false&showVersionInfo=false&dataFile=/post/2653785385/photoset_xml/tumblr_lepsihc2RV1qbclqg/500
I want it to appear like this:
http://mydomain.com/post/2653785385/photoset_xml/tumblr_lepsihc2RV1qbclqg/500
var str = 'showLogo=false&showVersionInfo=false&dataFile=/post/2653785385/photoset_xml/tumblr_lepsihc2RV1qbclqg/500';
str = 'http://mydomain.com' + str.split('&dataFile=')[1];
Example: http://jsfiddle.net/52z2z/
Here it splits the string on '&dataFile=', gets the last item in the resulting Array, and concatenates it do your domain.
You could also do this in Javascript using regular expressions:
var url = "showLogo=false&showVersionInfo=false&dataFile=/post/2653785385/photoset_xml/tumblr_lepsihc2RV1qbclqg/500";
var matches = url.match(/dataFile=(.*)/);
var what_you_need = "http://mydomain.com" + matches[1];
HTH

Categories