Javascript : Get value of first and second slash - javascript

How do i get first and second slash of a URL in javascript?
URL : http://localhost:8089/submodule/module/home.html
Now i want the value /submodule/module
Below is the code i have been trying
window.location.pathname.substring(0, window.location.pathname.indexOf("/",2))
This got me only /submodule
window.location.pathname.substring(0, window.location.pathname.lastIndexOf("/",window.location.pathname.lastIndexOf("/")-1))
Also this didnt work. Can anyone please guide where i am going wrong.

This should work, it take everything exept the last element of pathname:
let result = window.location.pathname.split('/').slice(0,-1).join('/') + '/'
Only the 1st and 2de item:
let result = window.location.pathname.split('/').slice(0,2).join('/') + '/'
Handle path without file :
// ex: /foo/bar/path.html > foo/bar/
// ex: /foo/bar/ > foo/bar/
let result = (window.location.pathname[window.location.pathname.length -1] !== '/') ? window.location.pathname.split('/').slice(0,-1).join('/') + '/' : window.location.pathname

You can use the split() function, for example like this:
var url = 'http://localhost:8089/submodule/module/home.html';
var parts = url.split('/');
console.log('/' + parts[3] + '/' + parts[4]);
The output will be:
/submodule/module

Try this:
var pathParts = window.location.pathname.split('/');
var result = `${pathParts[1]}/${pathParths[2]}`;

Using a regular expression:
var url = 'http://localhost:8089/submodule/module/home.html'; //or window.location.pathname
var re = /\/\/.+(\/.+\/.+)\/.+/
re.exec(url)[1];
This expression basically says the url is in the format
//[anything](/submodule/module)/[anything]
and to get everything in parentheses.

Functional style
/\/[^/]*\/[^/]*/.exec(window.location.pathname)[0]

You could use a regular expression:
var url = ...
var part = url.match(/https?:\/\/.*?(\/.*?\/.*?)\/.*/)[1]
Explanation:
http Match the group 'http'
s? Match 1 or 0 's'
: Match a semicolon
\/\/ Match '//'
.*? Match anything (non-greedy)
( Start capturing block (Everything captured will be an array element)
\/*?\/.*? Something that looks like /.../...
) End capturing block
\/.* Something that looks like /...
The output of the match method will be an array with 2 elements. The first one is the whole matched string, and the second is the captured group.

Related

Get last part of url with / at the end

I'm trying to get the last part of this url:
http://webserver/Foo/login/
the code that I wrote:
var location = window.location.href.split('/').pop();
will return an empty string 'cause after the / there is nothing.
I need to get at least the previous part, so in this case, login.
How can I do this?
The solution using String.replace()(used to replace possible / at the end of the string) and String.split() functions:
var url = 'http://webserver/Foo/login/',
last_section = url.replace(/\/+$/, '').split('/').pop();
console.log(last_section);
const getLastPartURL = url => {
const parts = url.split('/');
const length = parts.length;
return parts[length - 1] == '' ? parts[length - 2] : parts[length - 1]
}
console.log(getLastPartURL('http://webserver/Foo/login/'))
console.log(getLastPartURL('http://webserver/Foo/login'))
console.log(getLastPartURL('http://webserver/Foo/'))
console.log(getLastPartURL('http://webserver/Foo'))
This should do the trick:
location.pathname.match(/[^/]*(?=\/*$)/)[0]
Explanation:
Location.pathname is a string containing an initial '/' followed by the path of the URL.
String.prototype.match(regexp) returns an array of the matches.
[^/]* matches anything but a slash, and that zero or more times.
(?=\/*$) matches a slash zero or more times at the end of the string, while not including it.
There is always exactly one match, so we retrieve it with [0].
Example:
For all these URLs the output is login:
http://webserver/Foo/login
http://webserver/Foo/login/
http://webserver/Foo/login//

Remove last element from url

I need to remove the last part of the url from a span..
I have
<span st_url="http://localhost:8888/careers/php-web-developer-2"
st_title="PHP Web Developer 2" class="st_facebook_large" displaytext="facebook"
st_processed="yes"></span></span>
And I need to take the st_url and remove the php-web-developer-2 from it so it is just http://localhost:8888/careers/.
But I am not sure how to do that. php-web-developer-2 will not always be that but it won't have any / in it. It will always be a - separated string.
Any Help!!??
as simple as this:
var to = url.lastIndexOf('/');
to = to == -1 ? url.length : to + 1;
url = url.substring(0, to);
Here is a slightly simpler way:
url = url.slice(0, url.lastIndexOf('/'));
$('span').attr('st_url', function(i, url) {
var str = url.substr(url.lastIndexOf('/') + 1) + '$';
return url.replace( new RegExp(str), '' );
});
DEMO
Use this.
$('span').attr('st_url', function(i, url) {
var to = url.lastIndexOf('/') +1;
x = url.substring(0,to);
alert(x);
})​
You can see Demo
You could use a regular expression to parse the 'last piece of the url':
var url="http://localhost:8888/careers/php-web-developer";
var baseurl=url.replace(new RegExp("(.*/)[^/]+$"),"$1");
The RegExp thing basically says: "match anything, then a slash and then all non-slashes till the end of the string".
The replace function takes that matching part, and replaces it with the "anything, then a slash" part of the string.
RegexBuddy has a great deal of information on all this.
You can see it work here: http://jsfiddle.net/xKxLR/
var url = "http://localhost:8888/careers/php-web-developer-2";
var regex = new RegExp('/[^/]*$');
console.log(url.replace(regex, '/'));
First you need to parse the tag. Next try to extract st_url value which is your url. Then use a loop from the last character of the extracted url and omit them until you see a '/'. This is how you should extract what you want. Keep this in mind and try to write the code .

How do I extract data from this URL using javascript?

I need to build a string from the data contained in this url using javascript/jQuery:
http://www.example.com/members/admin/projects/?projectid=41
The string returned should look as follows:
/ajax/projects.php?projectid=41
Obviously if there is no query string present, the method should still return a string of the same format minus the query string. e.g.
http://www.example.com/members/admin/messages/
should return...
/ajax/messages.php
I've made numerous attempts, all met without success due to my poor grasp of regular expressions, and it feels as though the ore I rad on the subject the more I am confusing myself.
If someone could help it would be greatly appreciated.
EDIT: The 'admin' portion of the url is a users 'username' and could be anything.
Here's a function that will take your URL and return a new one according to the rules you've listed above:
function processURL(url) {
var base = "", query = "";
var matches = url.match(/([^\/\?]+)(\/$|$|\?|\/\?)/);
if (matches) {
base = matches[1];
matches = url.match(/\?[^\?]+$/);
if (matches) {
query = matches[0];
}
}
return("/ajax/" + base + ".php" + query);
}
And, a test app that shows it working on a bunch of URLs: http://jsfiddle.net/jfriend00/UbDfn/
Input URLs:
var urls = [
"http://www.example.com/members/admin/projects/?projectid=41",
"http://www.example.com/members/bob/messages/",
"http://www.example.com/members/jill/projects/",
"http://www.example.com/members/alice/projects?testid=99",
"http://www.example.com/members/admin/projects/?testid=99"
];
Output results:
/ajax/projects.php?projectid=41
/ajax/messages.php
/ajax/projects.php
/ajax/projects.php?testid=99
/ajax/projects.php?testid=99
To explain, the first regular expression looks for:
a slash
followed by one or more characters that is not a slash and not a question mark
followed by one of the four sequences
/$ a slash at the end of the string
$ end of the string
? a question mark
/? a slash followed by a question mark
The point of this regex is to get the last segment of the path that comes before either the end of the string or the query parameters and it's tolerant of whether the last trailing slash is there or not and whether there are any query parameters.
I know exactly what you are trying to do. In order to do it your way just split your string on question mark and then use last item form your array.
var data = your_url.split('?');
var newUrl = '/ajax/projects.php' + (data.length > 1 ? data[length-1] : "");
and you will have your url.
But what you can do is execute same url using your Script just add one parameter IsAjax=true and then check it in codebehind and execute your ajax logic.
e.g.
$('#somelink').onclick(function(){
$.ajax({ url: $(this).href, data { IsAjax: true } .... }
});
Using this way you will have more robust app.
I'll assume that by
http://www.example.com/members/admin/messages/
should return...
/ajax/members.php
you meant - should return...
/ajax/messages.php
If that is the case try
var query = url.split('?');
var paths = query[0].split('/');
var path = paths.pop();
if (path == '') //when there is trailing slash
path = paths.pop();
if (query.length == 1) //no query string
newurl = '/ajax/' + path + '.php';
else //query string
newurl = '/ajax/' + path + '.php?' + query[1];
I'm sure it can be made simpler and better, but that might give you a start.
var str = "http://www.example.com/members/admin/projects/?projectid=41";
var newStr = "/ajax/" + str.split("/").slice(-2).join(".php");
console.log(newStr);

Regex for parsing parameters from url

I'm a total noob with regexes and although I was trying hard I cannot create proper regexes to perform the following operation :
take url and check if it has a '?' followed by number with varying amount of digits.
if the match is correct, get the number after the '?' sign
exchange this number with different one.
So let's say we have this url :
http://website.com/avatars/avatar.png?56
we take '56' and change it to '57'.
I have the following regex for searching, I'm not sure if it's proper :
\?[0-9]+
But I have no idea how to take ? away. Should I just throw it away from the string and forget about using regex here ? Then the replace part is the only one left.
Try this:
var url = "http://website.com/avatars/avatar.png?56";
var match = url.match(/\?(\d+)/);
if(match != null) {
url = url.replace(match[1], "new number");
}
Your original regex will work just fine, just add back in the ? you are taking out like so:
var newnum = 57;
url = url.replace(/\?[0-9]+/, '?'+ newnum);
I'm no regex expert but I think you can use a lookaround to ignore the '?'
(?<=?)([0-9]+)
which should give you your number in the first match
VERY dummied-down approach:
$('#parse').click(function(e){
var fromUrl = $('#from-url').val();
var newNum = parseInt($('#new-number').val(), 10);
var urlRE = /(?!\?)(\d+)$/;
if (urlRE.test(fromUrl)){
$('#result').text(fromUrl.replace(urlRE, newNum));
}else{
$('#result').text('Invalid URL');
}
});
DEMO
There are not extravagant check-sums, error-checking, etc. Fromt here, use window.location or a string containing the URL if necessary.
Broken out in to a function (demo):
// Call this to replace the last digits with a new number within a url.
function replaceNumber(url, newNumber){
// regex to find (and replace) the numbers at the end.
var urlRE = /\?\d+$/;
// make sure the url end in a question mark (?) and
// any number of digits
if (urlRE.test(url)){
// replace the ?<number> with ?<newNumber>
return url.replace(urlRE, '?'+newNumber);
}
// invalid URL (per regex) just return same result
return url;
}
alert(replaceNumber('http://website.com/avatars/avatar.png?56', 57));
You could do this without regex.
var newNum = "57";
var url = "http://website.com/avatars/avatar.png?56";
var sUrl = url.split('?');
var rUrl = sUrl[0] + "?" + newNum;
alert(rUrl);
Split the URL at the ?
This returns an array.
Add the first item in the array and the ? and the new number back together.
http://jsfiddle.net/jasongennaro/7dMur/

How to extract the filename of the URL of the current document path in JavaScript?

I'm trying to extract the current file name in Javascript without any parameters.
$(location).attr('href').match(/([a-zA-Z\-\_0-9]+\.\w+)$/);
var current_path = RegExp.$1;
if ((current_path == 'index.html') || ...) {
// something here
}
But it doesn't work at all when you access like http://example.com/index.html?lang=ja. Sure before the file name will be changed at random.
Any idea?
If you're looking for the last item in the path, try this:
var current_path = window.location.pathname.split('/').pop();
This:
window.location.pathname
will give you something like:
"/questions/6543242/how-to-extract-the-filename-of-url-in-javascript"
Then the .split() will split the string into an Array, and .pop() will give you the last item in the Array.
function filename(path){
path = path.substring(path.lastIndexOf("/")+ 1);
return (path.match(/[^.]+(\.[^?#]+)?/) || [])[0];
}
console.log(filename('http://example.com/index.html?lang=ja'));
// returned value: 'index.html'
The filename of a URL is everything following the last "/" up to one of the following: 1.) a "?" (beginning of URL query), or 2.) a "#" (beginning of URL fragment), or 3.) the end of the string (if there is no query or fragment).
This tested regex does the trick:
.match(/[^\/?#]+(?=$|[?#])/);
There is a URL.js library that makes it very easy to work with URLs. I recommend it!
Example
var uri = new URI('http://example.org/foo/hello.html?foo=bar');
uri.filename(); // => 'hello.html'
your regex isn't correct. Instead try to be more specific:
.match(/([a-zA-Z\-\_0-9]+\.[a-zA-Z]{2,4})[\?\$]/);
says:
find any number of alphanumeric or hypens[a-zA-Z\-\_0-9]+ before a fullstop that has between 2 and 4 alphabetic characters [a-zA-Z]{2,4} that combefore either the end (\$) or a question mark (\?)
tested on:
("http://www.example.com/index.html?lang=ja").match(/([a-zA-Z\-\_0-9]+\.[a-zA-Z]{2,4})[\?\$]/);
var current_path = RegExp.$1;
alert(current_path);
try this:
window.location.pathname.substring(1)
You can do something more simple:
var url = "http://google.com/img.png?arg=value#div5"
var filename = url.split('/').pop().split('#')[0].split('?')[0];
Result:
filename => "img.png"

Categories

Resources