Replace date from url - javascript

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

Related

Get last two params of an URL - javascript

My URL looks like this
stackoverflow.com/questions/ask/format/return
I need to get only format/return from the above URL. I'm able to assign the complete URL to a variable. Currently i'm doing it on split
url.split("/")[4]
url.split("/")[5]
And this is not Generic. What is the better way to achieve this?
The shortest, cleanest way to do this is by using slice on the splitted URL:
url.split("/").slice(-2).join("/")
Just use the length to help you index from the end:
var res = url.split('/')
var last = res[res.length-1]
var pre_last = res[res.length-2]
A genetic solution,
Var URL = url.split("/"); //
Last = URL[URL.length-1]; // return
LastBefore = URL[URL.length-1]; //format
url = "stackoverflow.com/questions/ask/format/return"
URL = url.split("/");
console.log(URL[URL.length-1]) // return
console.log(URL[URL.length-2]) //format
Look for the last and penultimate values:
let spl = url.split("/");
alert(spl[spl.length-2]+' and '+spl[spl.length-1]);
I'd parse the url to a URL, then use match on the pathname. This way it will also work should you have any searchparams (?foo=bar) in your url
const s = "https://stackoverflow.com/questions/ask/format/return";
const uri = new URL(s);
const m = uri.pathname.match(/([^\/]*)\/([^\/]*)$/);
console.log(m);
Note that you'll get an array holding three entries - 0 being the path combined, 1 the first and 2 the last param.
You can use a simple regex /.*\/(.*\/.*)/) to extract exactly what you want.
str.match(/.*\/(.*\/.*)/).pop()
var str = "stackoverflow.com/questions/ask/format/return",
res = str.match(/.*\/(.*\/.*)/).pop();
console.log(res);
var parts = url.split("/");
lastTwo = [parts.pop(), parts.pop()].reverse().join("/");

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

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

Get the last part of an url in 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);
}

Categories