How to get current URL with JavaScript? [duplicate] - javascript

This question already has answers here:
Get current URL with jQuery?
(33 answers)
Closed 8 years ago.
I have this portion of the code. I want to know how can I read the url as the current page instead a fix url
Here is the portion of the coding:
var str='';
if(model_id != 0 ) str = model_id+"+";
if(year_id != 0 ) str +=year_id+"+";
url='http://store.ijdmtoy.com/SearchResults.asp?Search='+str;
top.location.href=url;
You see currently it has a fix reading the url http://store.ijdmtoy.com/SearchResults.asp
For example, I am currently on http://store.ijdmtoy.com/abs.htm
How can I change the code so it will automatically read as http://store.ijdmtoy.com/abs.htm?searching=Y&Search

If you are currently on http://store.ijdmtoy.com/abs.htm then document.URL will be http://store.ijdmtoy.com/abs.htm.
You can try:
url = location.protocol + '//' + location.host + location.pathname + '?Search=' + str;

You can use
document.URL or
window.location.href.toString()
I hope you mean this
http://jsfiddle.net/AmarnathRShenoy/q3yCA/

Use this code
document.URL
Ex:
alert(document.URL);
You can get path split like
var split=document.URL.split("/");

rather than using top.location.href=url;
you can use window.location = url;

var pathname = document.URL + 'Search=' + str;

Get it from window.location, as it is an object "cast it" to an string:
var global = (function(){ return this; })() ;
var str='';
if(model_id != 0 ) str = model_id+"+";
if(year_id != 0 ) str +=year_id+"+";
url= '' + global.location + '?Search='+str;
top.location.href=url;

If you just want to replace the query string use this:
window.location.search = "?searching="+str+"&Search";

you can use window.location.pathname

Related

Javascript - Remove some part of URL and Add Query after

How can I remove some part of an url and add some query before returning it?
Example:
locahost:8080/product/orders/1.
I want to remove the orders/1 and add /?query="sample".
Use replace function:
location.replace("locahost:8080/product/?query='sample'")
You can get the url by simply doing window.location.href. You can then edit it by copying it to some new var newURL = window.location.href;
newUrl = newUrl.replace('/orders/1', '/?query=\"sample\"');
window.location.href = newUrl; // execute this to pass on the parameters to the current page.
Suppose you have url like this in variable1, let say like this
var variable1 = 'http://locahost:8080/product/orders/1'; //here you can get the actual browser url using `window.location.href`and assign it to `variable1`
just use replace function:
var final_text = variable1.replace('/orders/1','?query=sample');
you will get the following output, you do console.log(final_text);
http://locahost:8080/product?query=sample
You can try something like
var url = window.location.href;
var query = "somestring" ;
window.location.replace(url + "&" + somestring);
removing the / pieces:
var newloc = url.substring(0, url.search("/")) + query;
window.location.replace(newloc);

jquery find and replace last parameter from a url

Hi first of all I've already looked around but there is nothing that matched what I want to happen, so I'm asking if anyone can help me with this.
I have a URL "/view/album/4/photo/1"
and i want to remove the last parameter and replace it with something.
What i want to do is to find the last "/" and remove the number after it and replace it with a new value.
It's easy with php but i don't know how to do it in jquery since I just started learning it. So I'd really appreciate anyone who can help. :)
By the way this is my code in getting the url:
action = $(form).attr('action'); // "/view/album/4/photo/1"
I don't know what to do with the variable to change the value of the last param
Try this :) http://jsfiddle.net/hE6MC/
OR http://jsfiddle.net/YwG6b/
API: http://www.w3schools.com/jsref/jsref_lastindexof.asp
BTW I knw about :) http://w3fools.com
code
url = "/view/album/4/photo/1"
var value = url.substring(url.lastIndexOf('/') + 1);
alert(value);
url = url.replace(value, 'hulk')
alert("new url => " + url);​
another way
var str = '/view/album/4/photo/1';
var i = str.lastIndexOf('/');
if (i != -1) {
str = str.substr(0, i) + "/new stuff";
}
alert(str);
​
var paths = location.pathname.split('/');
paths[ paths.length-1 ] = 'foo'; // new value
location.pathname = paths.join('/');
Easy and simple: regexp.
action = (action.match(/(.*)\d+$/) == null) ? action : (action.match(/(.*)\d+$/)[1]+"2");
gives
/view/album/4/photo/2
If you only wants to replace last character you can use slice method.
$('form').attr('action', function(i, a){
a.slice(0, -1) + 'number'
})

Can I do string formatting in Javascript? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
JavaScript equivalent to printf/string.format
I am creating code like this:
var ds = "ds=" + encodeURIComponent($('#DataSource').val());
var ex = "ex=" + encodeURIComponent($('#EID').val());
var to = "to=" + encodeURIComponent($('#TID').val());
var st = "st=" + encodeURIComponent($('#SID').val());
window.location.href = '/person?' + ds + "&" + ex + "&" + to + "&" + st;
Is there some way in Javascript that I could use formatting to make the code look a bit cleaner? Also do I need to encode each element or can I just encode the variable abc?
There's not a lot you can do, really. You could alias the encodeURIComponent method and use an array with join() if you're looking for something a little neater:
var e = encodeURIComponent,
arr = [
"ds=" + e($('#DataSource').val()),
"ex=" + e($('#EID').val()),
"to=" + e($('#TID').val()),
"st=" + e($('#SID').val())
];
window.location.href = '/person?' + arr.join("&");
Use <form> and put your input tags in them and you can call $('formContainer').serialize();
Its better to use name-value pairs(query strings), while sending data to URI. provide names as id to all of the input tags that you wish to capture. You will get something like:
/person/DataSource=ds&EID=ex&TID=to&SID=st
-HTH
Why don't you just write:
window.location.href = encodeURIComponent('/person?' +
$('#DataSource').val() + "&"
+ $('#EID').val() + "&" + $('#TID').val() + "&"
+ $('#SID').val());
Take a look at sprintf()
Also this can help: JavaScript equivalent to printf/string.format
var str = "/person?ds=%x&ex=%x&to=%x&st=%x";
var tokens = [
$("#DataSource").val(),
$("#EID").val(),
$("#TID").val(),
$("#SID").val()
];
tokens.forEach(function (token) {
str = str.replace("%x", encodeURIComponent(token));
});
location.href = str;
This will absolutely fall over if you have %x in your token string.
If you want a more generic solution try underscore.string

How to replace a space in a URL in JavaScript?

These are the 2 relevant lines from a function written in JavaScript:
var v_depttime = document.getElementById("EDDepttime").value ;
url = url+"?select_bno="+v_busno+"&select_depttime="+v_depttime ;
It sends the select_depttime as 2010-01-24 14:30:00
and I want it to be an URL encoded string like 2010-01-24%2014:30:00
How is it done in JavaScript?
Use encodeURI or encodeURIComponent.
Use encodeURIComponent:
url = url +
"?select_bno=" + encodeURIComponent(v_busno) +
"&select_depttime=" + encodeURIComponent(v_depttime);

How to strip all parameters and the domain name from a URL using javascript?

Given a series of URLs
http://www.anydotcom.com/myfolder/some-url.html
http://www.anydotcom.com/myfolder2/index.html#
http://www.anydotcom.com/myfolder3/index.html?someParam=aValue
http://www.anydotcom.com/foldername/index.html?someParam=anotherValue
First, how could I strip anything off the end of the URL so that I end up with
http://www.anydotcom.com/myfolder/some-url.html
http://www.anydotcom.com/myfolder2/index.html
http://www.anydotcom.com/myfolder3/index.html
http://www.anydotcom.com/foldername/index.html
or, ideally, I would like it to return
/myfolder/some-url.html
/myfolder2/index.html
/myfolder3/index.html
/foldername/index.html
I've tried
var thisUrl = "" + window.location;
var myRegExp = new RegExp("([^(\?#)]*)");
thisUrl = myRegExp.exec(thisUrl);
but this returns
http://www.anydotcom.com/foldername/index.html,http://www.anydotcom.com/foldername/index.html
and I don't quite understand why.
I appreciate any help here!
Well, to answer your question directly, here's the regular expression to do that.
thisUrl = thisUrl.replace( /^https?:\/\/[^\/]|\?.*$/g, '' );
However, since you mention window.location in your code, you can actually get this data straight from the location object.
thisUrl = top.location.pathname;
If you are using window.location, you can simply access the wanted data by using:
var thisUrl = window.location.pathname;
If you are extracting stuff from links, the following regular expression will get you what you need:
// Supports all protocols (file, ftp, http, https, whatever)
var pathExtract = /^[a-z]+:\/\/\/?[^\/]+(\/[^?]*)/i;
var thisUrl = (pathExtract.exec(someUrl))[1];
Javascript location object
var loc = window.location;
var thisUrl = loc.protocol + "//" + loc.hostname + loc.pathname;
using the object window.location is simple as write:
function getPath() {
return window.location.pathname;
}

Categories