I have a series of pages where I need to get a specific code for a button.
I want to put the code which is in the url into a variable with jQuery.
An example URL is www.example.com/folder/code/12345/
I want to get the number part in a variable called (siteCode)
Thanks in advance for any answers.
jquery / Pseudo code:
var siteCode;
// start function
function imageCode(){
siteCode // equals number part of URL
$('.button').attr('src', 'http:www.example.com/images/'+siteCode+'.jpg');
}
You can use the following code to get the last part of the url.:
var value = url.substring(url.lastIndexOf('/') + 1);
I'd suggest:
var URI = 'www.example.com/folder/code/12345/',
parts = URI.split('/'),
lastPart = parts.pop() == '' ? parts[parts.length - 1] : parts.pop();
JS Fiddle demo.
var str="url";
str.split("/")[3]
you can use split
There is one best way to take last part of URL is like following which generally has been used in real implementation.
There are Some loopholes in previously given answer was:
1.Consider what if there is a url like www.example.com/folder/code/12345 (Without '/' forward slash) Than none of the above code will work as per expectation.
2.Consider if folder hierarchy increases like www.example.com/folder/sub-folder/sub-sub-folder/code/12345
$(function () {
siteCode = getLastPartOfUrl('www.example.com/folder/code/12345/');
});
var getLastPartOfUrl =function($url) {
var url = $url;
var urlsplit = url.split("/");
var lastpart = urlsplit[urlsplit.length-1];
if(lastpart==='')
{
lastpart = urlsplit[urlsplit.length-2];
}
return lastpart;
}
Also try using regex
var url = "www.example.com/folder/code/12345";
var checkExt = /\d$/i.test(url);
if (checkExt) {
alert("Yup its a numeric");
} else {
alert("Nope");
}
Related
i want to modify url values based on some condition
(1)If my current url is http://example.com
then i have to add ?order=new to the url for this i write the following code and it is working
var url=window.location.href;
url=url+"order=new";
(2)If my current url is http://example.com/?class=1
then i have to add &order=new to the url for this i write the following code and it is working
var url=window.location.href;
if(url.indexOf("class=") >= 0){
url=url+"&order=new";
}
(3)If my current url is http://example.com/?class=1&order=new
then i have to add &order=date to the url for this i write the following code and it is working
var url=window.location.href;
if (url.indexOf("order=") >=0){
url= url.split("order=")[0]+"order=date";
}
(4) If my curent url is http://example.com/?class=anyvalue&div=anyvalue&order=anyvalue or http://example.com/?class=anyvalue&order=anyvalue&div=anyvalue. Here how can i replace order value ?
ie
http://example.com/?class=anyvalue&div=anyvalue&order=anything
http://example.com/?class=anyvalue&order=anything&div=anyvalue
Please support
Use URL
var url = window.location.href;
var urlObj = new URL( url );
Now you can search parameters of the URL
var order = urlObj.searchParams.get("order");
if ( !order )
{
//url += url.contains( "?" ) ? "&order=new" : "?order=new";
//contains didnt work so used includes instead
url += url.includes( "?" ) ? "&order=new" : "?order=new";
}
Similarly, you can replace value as well
var order = urlObj.searchParams.get("order");
if ( order )
{
urlObj.searchParams.set("order", "123");
}
console.log( urlObj.href );
Update:
added jsfiddle to your solution :)...
jsfiddle link
As far as I can say, I think you want this:
var url = 'http://example.com/?class=anyvalue&order=anything&div=anyvalue';
if (url.indexOf("order=") >= 0 && url.indexOf('div=') >= 0){
newUrl = url.replace('order=anything', 'order=456');
}
using replace() function. Change the url to what you are using.
I've run into some problems accessing and forwarding an ID.
I successfully extracted the ID from my URL but I run into problems if the URL contains unpredictable numbers aswell.
To clear things up a bit:
My efforts to extract the ID so far (JS)
var idString = window.location.href;
idString = idString.replace(/e107/gi, "__ersetzt__");
idString = idString.replace("http://localhost/Westbomke/backendV5/", "");
idString = idString.replace(/[^0-9]+/g, "");
Some URL examples
Working:
http://localhost/Westbomke/backendV5/e107-master/e107_projekte/BMW/235_Projekt_BMW-Event/page.php Result: 235 = id
Not working:
localhost/Westbomke/backendV5/e107-master/e107_projekte/BMW/235_Projekt_BMW-Event01/page.php
localhost/Westbomke/backendV5/e107-master/e107_projekte/company1337/235_Projekt_1337Event/page.php
now if I could exclude the /******_Projekt_ Part (**** = random amount of numbers) and parse it into an Integer I would be fine, but I dont know how to do this or if it's possible.
I tried to find something on here and via google but I most likely dont ask for the right stuff.
Thanks for your time and help in advance!
You can try with:
var url = 'http://localhost/Westbomke/backendV5/e107-master/e107_projekte/BMW/235_Projekt_BMW-Event/page.php';
var id = +url.match(/\/(\d+)/)[1];
Is this URL you are working on stable in terms of structure?
If you are nto familiar with Regular Expressions and the Structure is pretty stable , then the following code will do the job for you:
var myString = "http://localhost/Westbomke/backendV5/e107-master/e107_projekte/BMW/235_Projekt_BMW-Event/page.php";
var mySplitString = myString.split("/");
var myNumber = parseInt(mySplitString[8]);
console.log(myNumber);
Adding the below Function which will provide you with a bit more flexibility.
var myString = "http://localhost/Westbomke/backendV5/e107-master/e107_projekte/BMW/235_Projekt_BMW-Event/page.php";
function getProject(myString , myDist){
var mySplitString = myString.split("/");
var myID = '';
mySplitString.forEach(function(key , index){
if(key.indexOf(myDist) > 0)
myID = parseInt(mySplitString[index]);
});
return myID;
}
var myID = getProject(myString , "Projekt");
console.log(myID);
On my website:
http://mywebsite.com/1.html
I want to use the
window.location.pathname
to get the last part of the url:
1.html
and since I have all my webpages in numbers I want to add 1 to the current url so that when I click a button it will redirect me to the next page:
var url = 'http://mywebsite.com/' + window.location.pathname;
function nextImage (){
url = url + 1;
}
any ideas why this is not working ?
Your example wasn't working because you are trying to add 1 to a string that looks like this: "1.html". That will just get you this "1.html1" which is not what you want. You have to isolate the numeric part of the string and then convert it to an actual number before you can do math on it. After getting it to an actual number, you can then increase its value and then combine it back with the rest of the string.
You can use a custom replace function like this to isolate the various pieces of the original URL and replace the number with an incremented number:
function nextImage() {
return(window.location.href.replace(/(\d+)(\.html)$/, function(str, p1, p2) {
return((Number(p1) + 1) + p2);
}));
}
You can then call it like this:
window.location.href = nextImage();
Demo here: http://jsfiddle.net/jfriend00/3VPEq/
This will work for any URL that ends in some series of digits followed by .html and if you needed a slightly different URL form, you could just tweak the regular expression.
This is more robust:
mi = location.href.split(/(\d+)/);
no = mi.length - 2;
os = mi[no];
mi[no]++;
if ((mi[no] + '').length < os.length) mi[no] = os.match(/0+/) + mi[no];
location.href = mi.join('');
When the URL has multiple numbers, it will change the last one:
http://mywebsite.com/8815/1.html
It supports numbers with leading zeros:
http://mywebsite.com/0001.html
Example
Even it is not a good way of doing what you want try this hint:
var url = MUST BE A NUMER FIRST
function nextImage (){
url = url + 1;
location.href='http://mywebsite.com/' + url+'.html';
}
What you're doing is appending a "1" (the string) to your URL. If you want page 1.html link to page 2.html you need to take the 1 out of the string, add one to it, then reassemble the string.
Why not do something like this:
var url = 'http://mywebsite.com/1.html';
var pageNum = parseInt( url.split("/").pop(),10 );
var nextPage = 'http://mywebsite.com/'+(pageNum+1)+'.html';
nextPage will contain the url http://mywebsite.com/2.html in this case. Should be easy to put in a function if needed.
I am looking to write a piece of javascript that will append a parameter to the current URL and then refresh the page - how can I do this?
this should work (not tested!)
var url = window.location.href;
if (url.indexOf('?') > -1){
url += '¶m=1'
}else{
url += '?param=1'
}
window.location.href = url;
Shorter than the accepted answer, doing the same, but keeping it simple:
window.location.search += '¶m=42';
We don't have to alter the entire url, just the query string, known as the search attribute of location.
When you are assigning a value to the search attribute, the question mark is automatically inserted by the browser and the page is reloaded.
Most of the answers here suggest that one should append the parameter(s) to the URL, something like the following snippet or a similar variation:
location.href = location.href + "¶meter=" + value;
This will work quite well for the majority of the cases.
However
That's not the correct way to append a parameter to a URL in my opinion.
Because the suggested approach does not test if the parameter is already set in the URL, if not careful one may end up with a very long URL with the same parameter repeated multiple times. ie:
https://stackoverflow.com/?¶m=1¶m=1¶m=1¶m=1¶m=1¶m=1¶m=1¶m=1¶m=1
at this point is where problems begin. The suggested approach could and will create a very long URL after multiple page refreshes, thus making the URL invalid. Follow this link for more information about long URL What is the maximum length of a URL in different browsers?
This is my suggested approach:
function URL_add_parameter(url, param, value){
var hash = {};
var parser = document.createElement('a');
parser.href = url;
var parameters = parser.search.split(/\?|&/);
for(var i=0; i < parameters.length; i++) {
if(!parameters[i])
continue;
var ary = parameters[i].split('=');
hash[ary[0]] = ary[1];
}
hash[param] = value;
var list = [];
Object.keys(hash).forEach(function (key) {
list.push(key + '=' + hash[key]);
});
parser.search = '?' + list.join('&');
return parser.href;
}
With this function one just will have to do the following:
location.href = URL_add_parameter(location.href, 'param', 'value');
If you are developing for a modern browser, Instead of parsing the url parameters yourself- you can use the built in URL functions to do it for you like this:
const parser = new URL(url || window.location);
parser.searchParams.set(key, value);
window.location = parser.href;
location.href = location.href + "¶meter=" + value;
This line of JS code takes the link without params (ie before '?') and then append params to it.
window.location.href = (window.location.href.split('?')[0]) + "?p1=ABC&p2=XYZ";
The above line of code is appending two params p1 and p2 with respective values 'ABC' and 'XYZ' (for better understanding).
function gotoItem( item ){
var url = window.location.href;
var separator = (url.indexOf('?') > -1) ? "&" : "?";
var qs = "item=" + encodeURIComponent(item);
window.location.href = url + separator + qs;
}
More compat version
function gotoItem( item ){
var url = window.location.href;
url += (url.indexOf('?') > -1)?"&":"?" + "item=" + encodeURIComponent(item);
window.location.href = url;
}
Please check the below code :
/*Get current URL*/
var _url = location.href;
/*Check if the url already contains ?, if yes append the parameter, else add the parameter*/
_url = ( _url.indexOf('?') !== -1 ) ? _url+'¶m='+value : _url+'?param='+value;
/*reload the page */
window.location.href = _url;
One small bug fix for #yeyo's thoughtful answer above.
Change:
var parameters = parser.search.split(/\?|&/);
To:
var parameters = parser.search.split(/\?|&/);
Try this
var url = ApiUrl(`/customers`);
if(data){
url += '?search='+data;
}
else
{
url += `?page=${page}&per_page=${perpage}`;
}
console.log(url);
Also:
window.location.href += (window.location.href.indexOf('?') > -1 ? '&' : '?') + 'param=1'
Just one liner of Shlomi answer usable in bookmarklets
I am trying to use the youtube data api to generate a video playlist.
However, the video urls require a format of:
youtube.com/watch?v=3sZOD3xKL0Y
but what the api generates is:
youtube.com/watch?v=3sZOD3xKL0Y&feature=youtube_gdata
So what I need to do is be able to select everything after and including the ampersand(&) and remove it from the url.
Any way to do this with javascript and some sort of regular expression?
What am I missing?
Why not:
url.split('?')[0]
Hmm... Looking for better way... here it is
var onlyUrl = window.location.href.replace(window.location.search,'');
Example: http://jsfiddle.net/SjrqF/
var url = 'youtube.com/watch?v=3sZOD3xKL0Y&feature=youtube_gdata';
url = url.slice( 0, url.indexOf('&') );
or:
Example: http://jsfiddle.net/SjrqF/1/
var url = 'youtube.com/watch?v=3sZOD3xKL0Y&feature=youtube_gdata';
url = url.split( '&' )[0];
Use this function:
var getCleanUrl = function(url) {
return url.replace(/#.*$/, '').replace(/\?.*$/, '');
};
// get rid of hash and params
console.log(getCleanUrl('https://sidanmor.com/?firstname=idan&lastname=mor'));
If you want all the href parts, use this:
var url = document.createElement('a');
url.href = 'https://developer.mozilla.org/en-US/search?q=URL#search-results-close-container';
console.log(url.href); // https://developer.mozilla.org/en-US/search?q=URL#search-results-close-container
console.log(url.protocol); // https:
console.log(url.host); // developer.mozilla.org
console.log(url.hostname); // developer.mozilla.org
console.log(url.port); // (blank - https assumes port 443)
console.log(url.pathname); // /en-US/search
console.log(url.search); // ?q=URL
console.log(url.hash); // #search-results-close-container
console.log(url.origin); // https://developer.mozilla.org
//user113716 code is working but i altered as below. it will work if your URL contain "?" mark or not
//replace URL in browser
if(window.location.href.indexOf("?") > -1) {
var newUrl = refineUrl();
window.history.pushState("object or string", "Title", "/"+newUrl );
}
function refineUrl()
{
//get full url
var url = window.location.href;
//get url after/
var value = url = url.slice( 0, url.indexOf('?') );
//get the part after before ?
value = value.replace('#System.Web.Configuration.WebConfigurationManager.AppSettings["BaseURL"]','');
return value;
}
This worked for me:
window.location.replace(window.location.pathname)
No splits.. :) The correct/foolproof way is to let the native browser BUILT-IN functions do the heavy lifting using urlParams, the heavy lifting is done for you.
//summary answer - this one line will correctly replace in all current browsers
window.history.replaceState({}, '', `${location.pathname}?${params}`);
// 1 Get your URL
let url = new URL('https://tykt.org?unicorn=1&printer=2&scanner=3');
console.log("URL: "+ url.toString());
// 2 get your params
let params = new URLSearchParams(url.search);
console.log("querys: " + params.toString());
// 3 Delete the printer param, Query string is now gone
params.delete('printer');
console.log("Printer Removed: " + params.toString());
// BELOW = Add it back to the URL, DONE!
___________
NOW Putting it all together in your live browser
// Above is a breakdown of how to get your params
// 4 then you simply replace those in your current browser!!
window.history.replaceState({}, '', `${location.pathname}?${params}`);
Sample working Javascript Fiddle here
You could use a RegEx to match the value of v and build the URL yourself since you know the URL is youtube.com/watch?v=...
http://jsfiddle.net/akURz/
var url = 'http://youtube.com/watch?v=3sZOD3xKL0Y';
alert(url.match(/v\=([a-z0-9]+)/i));
Well, I am using this:
stripUrl(urlToStrip){
let stripped = urlToStrip.split('?')[0];
stripped = stripped.split('&')[0];
stripped = stripped.split('#')[0];
return stripped;
}
or:
stripUrl(urlToStrip){
return urlToStrip.split('?')[0].split('&')[0].split('#')[0];
}
For example we have:
example.com/list/search?q=Somethink
And you need use variable url like this by window.location.href:
example.com/list/edit
From url:
example.com/list/search?q=Somethink
example.com/list/
var url = (window.location.href);
url = url.split('/search')[0];
url = (url + '/edit');
This is simple solution:-)