Get data from URL with Javascript RegExp - javascript

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);

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.

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.

Deal with query strings in JS, like http_build_query, etc

Here's what I have
if(condition1) {
location.href = location.href+'/?site_type=normal';
}
else if(condition2) {
location.href = location.href+'/?site_type=other';
}
Of course, if the location.href already has query vars on it, thats a problem, etc.
I need to
Find the vars from the query string
if site_type already exists, replace the value with either 'normal' or 'other'
rebuild the url with the new site_type
edit:
I found I needed to account for all kinds of URLs:
domain.com
domain.com/path/to/sth/
domain.com/?site_type=normal
domain.com?var=123&foo=987
domain.com/path/?site_type=normal&var=123&foo=987
So, here's what I came up with, suggestions welcome:
var searchstring = window.location.search;
var url = window.location.href;
console.log('search: ' + searchstring);
console.log( 'url: ' + url);
// strip search from url
url = url.replace(searchstring,"");
console.log( 'url: ' + url);
//strip site_type from search
searchstring = searchstring.replace("&site_type=normal","")
.replace("&site_type=other","")
.replace("?site_type=normal","")
.replace("?site_type=other","")
.replace("?","")
;
console.log('search: ' + searchstring);
if(searchstring != ''){searchstring = '&' + searchstring;}
var final = url + '?site_type=normal' + searchstring;
final = final.replace("&&","&");
console.log('final: ' + final);
You can directly access the query string with window.location.search. You can convert it to an object using this regex trick found here.
var queryString = {};
window.location.search.replace(/([^?=&]+)(=([^&]*))?/g, function($0, $1, $2, $3) {
queryString[$1] = $3; }
);
Then set the site_type on queryString appropriately.
queryString["site_type"] = "normal";
And finally, convert it back into a string and set that as the window.location.search.
var searchString = "";
for ( q in queryString ) {
searchString+="&" + q + "=" + queryString[q];
}
window.location.search = searchString;
Here's a way to do this:
//remove existing param and append new one..
var newHref = window.location.href.replace(window.location.search,"") + '?site_type=other';
//change href
window.location.href = newHref;
works only if you have one parameter that you want to replace, otherwise it would remove all parameters.
for example if you have
yourpage.com/?site_type=normal
and you need only website not query vars you cans clear them
var novars= location.href.replace(window.location.search,"")
this case novars = youroage.com
for just getting variables u can do this:
var site_type = window.location.search.replace("?site_type=","");
here i will get site_type value whether its normal or other
this case your variable site_type = "normal"
for rebuilding url u can just add new site_type
location.href = novars+"?site_type=normal"
or
location.href = novars+"?site_type=other"

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/

Split URL in javascript at last instance of '&'

I saw a bunch of URL splitting techniques on this site but could find one for what i need.
I need the last parameter chopped off.
ie.
http://www.website.com/Pages/SearchResultsPage.aspx?k=website&cs=This%20Site&u=http%3A%2F%2Fwww.website.com%2FOur-Commitment
to
http://www.website.com/Pages/SearchResultsPage.aspx?k=website&cs=This%20Site
The URL will not always be the same and so the solution must somehow search for the last "&" and strip it off.
I managed to do this but i was hoping for less lines:
rewriteURL();
function rewriteURL() {
var url = window.location;
var urlparts = url.split(/[\s&]+/);
var newURL = urlparts[0] + '&' + urlparts[1];
window.location.href = newURL;
}
function rewriteURL() {
window.location.href = window.location.href.substring(0, window.location.href.lastIndexOf('&'));
}
var loc = window.location + '';
var url = loc.substring(0, loc.lastIndexOf('&'));
window.location is not a string.
The answer by #thejh is better, but for a fun one-liner:
var newLoc = location.href.split('&').slice(0,-1).join('&');
// "http://www.website.com/Pages/SearchResultsPage.aspx?k=website&cs=This%20Site"
function rewriteURL() {
var urlparts = window.location.href.split(/[\s&]+/);
window.location.href = urlparts[0] + '&' + urlparts[1];
}
(Point is, does it matter that much?)
My bigger concern would be that I'd be afraid the parameter order might change, or there'd be additional parameters, etc. Better to do it right and be certain.

Categories