Get the last part of an url in Javascript - javascript

Using the following URL example, how would I get the obtain the username from it?
http://www.mysite.com/username_here801
A regex solution would be cool.
The following sample only gets the domain name:
var url = $(location).attr('href');
alert(get_domain(url));
function get_domain(url) {
return url.match(/http:\/\/.*?\//);
}
jQuery solutions are also acceptable.

var url = "http://www.mysite.com/username_here801";
var username = url.match(/username_(.+)/)[1];
http://jsfiddle.net/5LHFd/
To always return the text directly after the slash that follows the .com you can do this:
var url = "http://www.mysite.com/username_here801";
var urlsplit = url.split("/");
var username = urlsplit[3];
http://jsfiddle.net/5LHFd/2/

You can access it with document.location.pathname

If a RegEx solution is acceptable, you could try:
function get_path(url) {
// following regex extracts the path from URL
return url.replace(/^https?:\/\/[^\/]+\//i, "").replace(/\/$/, "");
}

You could use your getDomain() function to find out where your pathname start.:
function getUsername(url){
var position = getDomain(url).length + 1;
return url.slice(position);
}

Related

Javascript - Remove some part of URL and Add Query after

How can I remove some part of an url and add some query before returning it?
Example:
locahost:8080/product/orders/1.
I want to remove the orders/1 and add /?query="sample".
Use replace function:
location.replace("locahost:8080/product/?query='sample'")
You can get the url by simply doing window.location.href. You can then edit it by copying it to some new var newURL = window.location.href;
newUrl = newUrl.replace('/orders/1', '/?query=\"sample\"');
window.location.href = newUrl; // execute this to pass on the parameters to the current page.
Suppose you have url like this in variable1, let say like this
var variable1 = 'http://locahost:8080/product/orders/1'; //here you can get the actual browser url using `window.location.href`and assign it to `variable1`
just use replace function:
var final_text = variable1.replace('/orders/1','?query=sample');
you will get the following output, you do console.log(final_text);
http://locahost:8080/product?query=sample
You can try something like
var url = window.location.href;
var query = "somestring" ;
window.location.replace(url + "&" + somestring);
removing the / pieces:
var newloc = url.substring(0, url.search("/")) + query;
window.location.replace(newloc);

How to strip / replace something from a URL?

I have this URL
http://192.168.22.124:3000/temp/box/c939c38adcf1873299837894214a35eb
I want to replace the last part of my URL which is c939c38adcf1873299837894214a35eb with something else.
How can I do it?
Try this:
var url = 'http://192.168.22.124:3000/temp/box/c939c38adcf1873299837894214a35eb';
somethingelse = 'newhash';
var newUrl = url.substr(0, url.lastIndexOf('/') + 1) + somethingelse;
Note, using the built-in substr and lastIndexOf is far quicker and uses less memory than splitting out the component parts to an Array or using a regular expression.
You can follow this steps:
split the URL with /
replace the last item of array
join the result array using /
var url = 'http://192.168.22.124:3000/temp/box/c939c38adcf1873299837894214a35eb';
var res = url.split('/');
res[res.length-1] = 'someValue';
res = res.join('/');
console.log(res);
Using replace we can try:
var url = "http://192.168.22.124:3000/temp/box/c939c38adcf1873299837894214a35eb";
var replacement = 'blah';
url = url.replace(/(http.*\/).*/, "$1" + replacement);
console.log(url);
We capture everything up to and including the final path separator, then replace with that captured fragment and the new replacement.
Complete guide:
// url
var urlAsString = window.location.href;
// split into route parts
var urlAsPathArray = urlAsString.split("/");
// create a new value
var newValue = "routeValue";
// EITHER update the last parameter
urlAsPathArray[urlAsPathArray.length - 1] = newValue;
// OR replace the last parameter
urlAsPathArray.pop();
urlAsPathArray.push(newValue);
// join the array with the slashes
var newUrl = urlAsPathArray.join("/");
// log
console.log(newUrl);
// output
// http://192.168.22.124:3000/temp/box/routeValue
You could use a regular expression like this:
let newUrl = /^.*\//.exec(origUrl)[0] + 'new_ending';

Replace date from url

I would like to write a javascript function that replace a date in the format YYYY/MM/DD from an url to a specific string.
var url = "http://localhost/reussitemlm/2015/09/08/comment-vous-eviter-de-perdre-votre-attractivite-aux-yeux-de-vos-prospects/";
var newUrl = replaceDate(url, 'qtvideo');
console.log(newUrl);
"http://localhost/reussitemlm/qtvideo/comment-vous-eviter-de-perdre-votre-attractivite-aux-yeux-de-vos-prospects/"
You can simply use a RegEx(d for digit) that searches for the expression dddd/dd/dd
let url = "http://localhost/reussitemlm/2015/09/08/comment-vous-eviter-de-perdre-votre-attractivite-aux-yeux-de-vos-prospects/",
date_format = /\d{4}\/\d{2}\/\d{2}/;
url = url.replace(date_format, "qtvideo");
console.log(url);
This is rather rudimentary and I'm sure that regex experts have better patterns but the following expression should match
/[0-9]{4}\/[0-9]{2}\/[0-9]{2}/
Use it like this
var url = "http://localhost/reussitemlm/2015/09/08/comment-vous-eviter-de-perdre-votre-attractivite-aux-yeux-de-vos-prospects/";
url.replace(/[0-9]{4}\/[0-9]{2}\/[0-9]{2}/, 'qtvideo');
function replaceDate(url,str){
let regex = /\d{4}[\/.]\d{1,2}[\/.]\d{1,2}/;
let res = url.replace(regex.exec(url)[0], str);
return res;
}
This should work for you ... thanks

parsing pathname in url.pathname()

I have a url as below
localhost:1340/promotionDetails/pwd1/pwd2?promotion_id=PROM008765
I used url module for parsing the url for the pathname below is the code
var url=require('url').parse('http://localhost:1340/promotionDetails/pwd1/pwd2? promotion_id=PROM008765', true).pathname
console.log(url);
The output that I got is
/promotionDetails/pwd1/pwd2
I used the split function to get the pwd1 and pwd2 from the path.I want to know if there is anyother way to get pwd1 and pwd2 without using the split function.Any help will be really helpful.
You can regex to get the url directories without using split.
var myurl = "localhost:1340/promotionDetails/pwd1/pwd2?promotion_id=PROM008765";
var match = myurl.match(/[^/?]*[^/?]/g);
/* matches everything between / or ?
[ 'localhost:1340',
'promotionDetails',
'pwd1',
'pwd2',
'promotion_id=PROM008765' ]
*/
console.log(match[2]);//pwd1
console.log(match[3]);//pwd2
Updated 2019 ES6 answer:
You can regex to get the url directories without using split.
const myurl = "localhost:1340/promotionDetails/pwd1/pwd2?promotion_id=PROM008765";
const filteredURL = myurl.match(/[^/?]*[^/?]/g).filter((urlParts) => {
return urlParts !== 'promotionDetails' && urlParts !== 'localhost:1340'
})
const [pwd1, pwd2] = filteredURL;
console.log(pwd1)
console.log(pwd2)

I need to match a certain part of url path using Regex and Javascript

I have the following link:
sitename.com/Default.aspx?PageID=13078494
I want to grab the following: "PageID=13078494". This is what I have so far:
var url = "sitename.com/Default.aspx?PageID=13078494";
urlmatch = url.match([PageID=13078494]);
urlmatch[0];
Is this the proper expression for what I'm trying to do?
Your regex and its syntax are wrong.
A better way would be to not use a regex at all. Use .split() instead:
var urlmatch = url.split('?')[1];
Here's the fiddle: http://jsfiddle.net/qpXNU/
var myregexp = /[?&]PageID=(\d+)/i;
var match = myregexp.exec(url);
if (match != null) {
//This is if your match it successful
result = match[1];
} else {
//This is if url doesn't match
result = "";
}
This one will work regardless of where PageID is. It will match
sitename.com/Default.aspx?PageID=13078494
anything.org/Default.aspx?PageID=13078494
sitename.com/Default.aspx?foo=bar&PageID=13078494
sitename.com/Default.html?foo=bar&PageID=13078494&bar=foo
Default.html?foo=bar&PageID=13078494&bar=foo
Importantly, it WON'T match
sitename.com/Default.aspx?NotThePageID=13078494
Or without the checking, simply
url.match(/[?&]PageID=(\d+)/i)[1], but I'd advice against that unless your SURE it will always match.
Try the following regex, which will extract the PageID and place it in the first match group:
var url = "sitename.com/Default.aspx?PageID=13078494";
urlmatch = url.match(/PageID=(\d+)/);
alert(urlmatch[1]);​ // 13078494
If you are matching specific value, then it's fine, otherwise use below to match any number of digits in pageID:
/PageID=\d+/
as:
var url = "sitename.com/Default.aspx?PageID=13078494";
var urlmatch = url.match(/PageID=\d+/);
alert(urlmatch[0]);
or to match 8 exact digits in pageID, use:
/PageID=\d{8}/
as:
var url = "sitename.com/Default.aspx?PageID=13078494";
var urlmatch = url.match(/PageID=\d{8}/);
alert(urlmatch[0]);
When it comes to handling URLs, the browser is pretty good.
You should convert your string to an actual URL like so:
var toURL = function (href) {
var a = document.createElement('a');
a.href = href;
return a;
};
Now use the browser's built-in parsing capabilities:
var url = toURL('sitename.com/Default.aspx?PageID=13078494');
alert(url.search);

Categories