I have url "SampleProject/profile/aA12". How can I get the value of the id from my rewritten URL using javascript? I want to get the "aA12" value.
Im using htaccess rewrite to rewrite my URL. Im new in rewritting url's. Any help will be appreciated. More powers and thank you.
You can use regex.
Try
'SampleProject/profile/aA12'.match(/\SampleProject\/profile\/(\w+)/)
'SampleProject/profile/aA12/xxx'.match(/\SampleProject\/profile\/(\w+)/)
'aA12' will be matched in both cases.
There are going to be quite a few ways to achieve your goal with JavaScript. A simple solution could be something like this:
let myURL = "SampleProject/profile/aA12";
let result = myURL.split('/').pop();
// returns "aA12"
The .split('/') method is dividing your string up into an array using the / character, and .pop() is simply returning the last element of that array.
Hope this helps! If you were looking for more advanced matching, i.e. if you wanted to ignore a potential query string on the end of the URL parameter, you could use regular expressions.
Their is a many way that you can use to achieve the desired method i made you a code pen in this link
var url = "SampleProject/profile/aA12";
let res = url.split('/').pop();
console.log(res)
https://codepen.io/anon/pen/KQxNja
Related
I only want to have the numbers of my URL as return. At the moment I use:
alert(document.URL);
to get the whole URL. But is there any other easy solution to get only the ID-Numbers from my URL as result? I also use jQuery and PHP in this project.
var numbers = document.URL.match(/\d+/g) will return all numbers in a URL (eg for this thread) document.URL.match(/\d+/g) => ["19570840"]
alert(document.URL.match(/\d+/g));
Simple. I would put it in a fiddle, but uhh, jsFiddle doesn't have any numbers in their url, so.
I know it is an easy one, sorry for asking, but I’m going mad and I cannot get it. Must be the fundamentals, I’ve got them all mix up :((
I have this url:
https://www.myweb.sub.com/~user/folder/file.php?param=Value
I need to get:
https://www.myweb.sub.com/~user/folder/
in a variable.
Please help to achieve it.
Thanks a lot
You can use the slice() and lastIndexOf() methods:
var url = "https://www.myweb.sub.com/~user/folder/file.php?param=Value";
var segment = url.slice(0, url.lastIndexOf("/") + 1);
If your current URL is actually https://www.myweb.sub.com/~user/folder/file.php?param=Value, operate on window.location.href instead.
So we don't chew it all up for you, here's a link that should set you on the right path:
find the last index of a character with this: http://www.w3schools.com/jsref/jsref_lastindexof.asp
get the substring of a string with this:
http://www.w3schools.com/jsref/jsref_substring.asp
Tell us if you still need help after that.
use this :-
var str="https://www.myweb.sub.com/~user/folder/file.php?param=Value";
var n=str.substring(0,str.indexOf("file"));
I want to find anything that comes after s= and before & or the end of the string. For example, if the string is
t=qwerty&s=hello&p=3
I want to get hello. And if the string is
t=qwerty&s=hello
I also want to get hello
Thank you!
\bs=([^&]+) and grabbing $1should be good enough, no?
edit: added word anchor! Otherwise it would also match for herpies, dongles...
Why don't you try something that was generically aimed at parsing query strings? That way, you can assume you won't run into the obvious next hurdle while reinventing the wheel.
jQuery has the query object for that (see JavaScript query string)
Or you can google a bit:
function getQuerystring(key, default_)
{
if (default_==null) default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
}
looks useful; for example with
http://www.bloggingdeveloper.com?author=bloggingdeveloper
you want to get the "author" querystring's value:
var author_value = getQuerystring('author');
The simplest way to do this is with a selector s=([^&]*)&. The inside of the parentheses has [^&] to prevent it from grabbing hello&p=3 of there were another field after p.
You can also use the following expression, based on the solution provided here, which finds all characters between the two given strings:
(?<=s=)(.*)(?=&)
In your case you may need to slightly modify it to account for the "end of the string" option (there are several ways to do it, especially when you can use simple code manipulations such as manually adding a & character to the end of the string before running the regex).
I'm using JavaScript to try and get the filename from the URL.
I can get it using this:
var fn=window.location.href.match(/([^/])+/g);
alert(fn[fn.length-1]); // get the last element of the array
but is there an easier way to get it (e.g., without having to use fn[fn.length-1]
Thanks!!
Add a $ at the end so you only get the last part:
window.location.href.match(/[^/]+$/g);
Personally, I try to use simple string manipulation for easy tasks like this. It makes for more readable code (for a person not very familiar with RegEx).
var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);
Or simply:
var filename = window.location.pathname.substring(window.location.pathname.lastIndexOf('/')+1);
Additional Information
Not that it matters for something so trivial, but this method is also more performant than RegEx: http://jsperf.com/get-file-name
How about:
window.location.href.match(/\/([^/]+)$/)[1];
you can use .pop() to get the last element of an array;
alert(fn.pop());
There is a jQuery plugin that makes it easy to parse URLs and provide access to their different parts. One of the things it does is return the filename. Here's the plugin on GitHub:
https://github.com/allmarkedup/jQuery-URL-Parser
I would recommend using that and avoid reinventing the wheel. Regular expressions is an area of programming where this is particularly applicable.
I recommend to also remove any '#' or '?' string, so my answer is:
var fn = window.location.href.split('/').pop().replace(/[\#\?].*$/,'');
alert(fn);
split('/').pop() removes the path
replace(/[\#\?].*$/,'') replace '#' or '?' until the end $ by empty string
We have a javascript function we use to track page stats internally. However, the URLs it reports many times include the page numbers for search results pages which we would rather not be reported. The pages that are reports are of the form:
http://www.test.com/directory1/2
http://www.test.com/directory1/subdirectory1/15
http://www.test.com/directory3/1113
Instead we'd like the above reported as:
http://www.test.com/directory1
http://www.test.com/directory1/subdirectory1
http://www.test.com/directory3
Please note that the numbered 'directory' and 'subdirectory' names above are just for example purposes and that the actual subdirectory names are all different, don't necessarily include numbers at the end of the directory name, and can be many levels deep.
Currently our JavaScript function produces these URLs using the code:
var page = location.hostname+document.location.pathname;
I believe we need to use the JavaScript replace function in combination with some regex but I'm at a complete loss as to what that would look like. Any help would be much appreciated!
Thanks in advance!
I think you want this:
var page = location.href.substring(0,location.href.lastIndexOf("/"));
You can use a regex for this:
document.location.pathname.replace(/\/\d+$/, "");
Unlike substring and lastIndexOf solutions, this will strip off the end of the path if it consists of digits only.
What you can do is find the last index of "/" and then use the substring function.
Not sure you need a regex if you're just pulling off the last slash + content.
http://www.w3schools.com/jsref/jsref_lastIndexOf.asp
I'd probably use that to search for the last "/" character, then do a substring from the start of the string to that index.
How about this:
var page = location.split("/");
page.pop();
page = page.join("/");
I would think you need to use the .htaccess with rewrite rules to change the look of the url, however I am still looking to see if this is available to javascript. Will repost when I find out more
EDIT*
the lastIndexOf would only give you the position, therefor you would still need to replace. ex:
var temp = page.substring(page.lastIndexOf("/"),page.length-1);
page = page.replace(temp, "");
unfortunately I'm not that advanced in my coding so there is probably more efficient coding in the other answers. Sorry for any inconveniences with my initial answer.