Javascript URL depth (level) - javascript

Is it possible to get url depth (level) with Javascript?
If I have this url:
www.website.com/site/product/category/item -> depth=4
www.website.com/site/product/category -> depth=3

I would use a regex to determine how many matches there are for a slash followed by one or more characters.
var url = "www.website.com/site/product/category/item";
url.match(/\/.+?/g).length; // returns 4
Edit: Added a few checks against query strings and double slashes. (credit to user Lix for sparking the idea)
var url = "www.website.com/site/product/category/item?url=/query/string/path";
url.split(/[?#]/).shift().match(/\/[^/]+?/g).length;

simply split it by "/" and check the length of returning array
var url = "www.website.com/site/product/category/item";
alert("depth is " + (url.split("/").length - 1));
url = "www.website.com/site/product/category"
alert("depth is " + (url.split("/").length - 1));

Related

javascript's String.length returns wrong character count

I came accross a strange javascript behavior today which is probably due to some character encoding issue. The length function returns two different character count for what is apparently the exact same string.
In one instance the string was copy pasted from a database value, in the second instance I manually wrote the characters with my keyboard.
I'm sure this is UTF related but I cant figure how to get the "correct" character count.
Is there a way to know which encoding the faulty string is in and "fix" it somehow?
Is there a way to force every strings in my app to be UTF-8 ?
Is there a hidden character somewhere ?
Thanks for your help
var utils = {
/**
* cleans up our url before db insertion
*
* #param url
* #returns {String} the cleaned url
*/
cleanUrl : function(url){
url = url.trim().toLowerCase();
if(url.includes('?'))return url;
var lastChar = url.charAt(url.length-1);
console.log('lastchar = ' + lastChar);
if(lastChar == '/'){
url=url.substring(0, url.length-1);
}
return url;
},
doTest : function(){
var url = "https://bitcointalk.org/‎"; //this string was taken from DB
console.log('url length ' + url.length);
console.log('url length ' + url.trim().length);
var cleaned = this.cleanUrl(url);
console.log('cleaned length ' + cleaned.length);
console.log('cleaned ' + cleaned);
console.log('------------------------------');
var url2 = "https://bitcointalk.org/"; //this string was manually written
console.log('url2 length ' + url2.length);
console.log('url2 length ' + url2.trim().length);
var cleaned2 = this.cleanUrl(url2);
console.log('cleaned2 length ' + cleaned2.length);
console.log('cleaned2 ' + cleaned2);
}
};
utils.doTest()
And here is the output :
url length 25
url length 25
lastchar = ‎
cleaned length 25
cleaned https://bitcointalk.org/‎
------------------------------
url2 length 24
url2 length 24
lastchar = /
cleaned2 length 23
cleaned2 https://bitcointalk.org
You are correct! There is a secret character encoded from the DB you can see if you copy both of your strings out and try it in your browser console.
I have tested your string which is copied from DB and it contains some special characters. So for that you can use encodeURIComponent() method of javascript on that string and then save that encoded string in DB and while retrieving perform decodeURIComponent() on that string.

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//

Replace ID in a URL between two markers

I have a url which looks like this:
I want to replace: 1034749-184e-3467-87e0-d7546df59896 with another ID, is there any regex or similar replace method which will allow me to replace the ID using JavaScript between the 'image/' and '?' characters?
You could make this approximation expression:
/[0-9a-z]+(?:-[0-9a-z]+){4}/i
Match a bunch of hexadecimals, followed by 4 sections, each starting with a dash followed by a bunch of hexadecimals.
> var s = 'http://url/images/1034749-184e-3467-87e0-d7546df59896?w=600&r=22036';
> console.log(s.replace(/[0-9a-z]+(?:-[0-9a-z]+){4}/i, 'something-else'));
http://url/images/something-else?w=600&r=22036
/images\/[^?]+/ would match, but it would replace images/ as well.
Fortunately you can pass a callback to .replace:
url.replace(/(images\/)[^?]+/, function($match, $1) {
// results in "images/<some-ID>"
return $1 + theNewId;
});
If you have a reference to the DOM element anyway, you can also just replace the last step of the path:
element.pathname =
element.pathname.substring(0, element.pathname.lastIndexOf('/') + 1) + newId;
Yes, just do this:
var url = document.getElementById("yoururlid").src;
url = url.split("/");
var newUrl = url[0] + url[1] + url[2] + url[3] + newURLID;
Why not just do this:
document.getElementById("yoururlid").src="http://url/images/" + newId + "?w=600&r=22036";

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/

Categories

Resources