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);
Related
I'm having trouble trying to find an item that has a hash (#), I want to change the hash in the url to another identifier. For example, I have a url like this => http://localhost:8088/stores/1/brands?q=# When searching with a hash, the url will change to something like this => http://localhost:8088/stores/1/brands?q=%23
How to replace like that and push it to current url?
let currentUrl = 'http://localhost:8088/stores/1/brands?q=#';
let url = new URL(currentUrl);
url.searchParams.set("q", "#"); // setting param
url.hash='';
let newUrl = url.href;
console.log(newUrl);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You can use the function encodeURIComponent.
E.g.
encodeURIComponent("#") // gives %23
You can read the detail on MDN docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
you can use replace
let currentUrl = "http://localhost:8088/stores/1/brands?q=#";
str = currentUrl.replace("#", "023");
console.log(str);
Update :
if you want to set the url you can use
location.href = str;
but in order to stop the infinite loop you need to add a extra para like
let currentUrl = "http://localhost:8088/stores/1/brands?q=#";
str = currentUrl.replace("#", "023");
console.log(str);
var hash = url.searchParams.get("hashset");
if(hash !== "1") {
console.log(str+"&hashset=1");
location.href = str+"&hashset=1";
} else {
console.log("hash already set")
}
For example:
example.com/fun/browse/apples/bananas
example.com/browse/gerbals/cooties
How can I find the keyword "browse", regardless of where it is in the url, and remove the following url part. In the above cases that would be "apples" and "gerbals"
I tried spliting it by the "/" and getting the indexOf browse, then removing the next item, but I cant seem to join everything together because that creates a double "//" in the new url.
Any help would be appreciated.
Javascript and jQuery both ok.
NOTE: I do not want to remove any other part of the url. I want to keep everything. I want to only remove the part of the url immediately after browse.
Your question is unclear but let's try :
var s = 'example.com/fun/browse/apples/bananas';
s.replace(/(\/browse)\/[^\/]+/, '$1'); // "example.com/fun/browse/bananas"
Also check this helper :
function removeAfter(s, keyword) {
return s.replace(
new RegExp('(\/' + keyword + ')\/[^\/]+'), '$1'
);
}
Usage :
var s = 'example.com/browse/gerbals/cooties';
removeAfter(s, 'browse'); // "example.com/browse/cooties"
removeAfter(s, 'gerbals'); // "example.com/browse/gerbals"
Demo : http://jsfiddle.net/wared/VRJtL/.
remove browser by using .splice() & rejoin it.
var arr = "example.com/fun/browse/apples/bananas".split('/');
var index = arr.indexOf("browse");
arr.splice(index+1,1); //removes apples
var URL = arr.join('/'); //joins back
result: "example.com/fun/browse/bananas"
Split the URL on the Keyword...
example:
var url = "http://www.foo.com/bar/alpha/beta";
var keyword = "alpha";
var result = url.split(keyword)[0];
//result = "http://www.foo.com/bar/" + keyword;
//adding the keyword is if you need the keyword in your response.
If you're not trying to remove 'fun' part, it's really simple:
var url = 'example.com/fun/browse/apples/bananas';
var result = url.replace(/browse\/[a-zA-Z\/]+/, 'browse/gerbals/cooties');
I'll throw out another option, just to make it interesting. :)
var url = "http://example.com/fun/browse/apples/bananas";
var targetWord = "browse";
var regexPattern = new RegExp("(^.*" + targetWord + "/?)[^/]*/?(.*$)");
var newURL = "";
var matchedURLparts = regexPattern.exec(url);
if (matchedURLparts) {
newURL = (matchedURLparts.length > 2) ? matchedURLparts[1] + matchedURLparts[2] : matchedURLparts[1];
}
else {
newURL = url;
}
Using the following URL example, how would I get the obtain the username from it?
http://www.mysite.com/username_here801
A regex solution would be cool.
The following sample only gets the domain name:
var url = $(location).attr('href');
alert(get_domain(url));
function get_domain(url) {
return url.match(/http:\/\/.*?\//);
}
jQuery solutions are also acceptable.
var url = "http://www.mysite.com/username_here801";
var username = url.match(/username_(.+)/)[1];
http://jsfiddle.net/5LHFd/
To always return the text directly after the slash that follows the .com you can do this:
var url = "http://www.mysite.com/username_here801";
var urlsplit = url.split("/");
var username = urlsplit[3];
http://jsfiddle.net/5LHFd/2/
You can access it with document.location.pathname
If a RegEx solution is acceptable, you could try:
function get_path(url) {
// following regex extracts the path from URL
return url.replace(/^https?:\/\/[^\/]+\//i, "").replace(/\/$/, "");
}
You could use your getDomain() function to find out where your pathname start.:
function getUsername(url){
var position = getDomain(url).length + 1;
return url.slice(position);
}
I have a URL like this:
http://www.url/name/something/#/venue
I need to grab the 'venue' from each URL. I have:
var currentUrl = $(location).attr('href');
var urlParts = currentUrl.split( "/" );
The split breaks up the URL.
I'm not sure how to grab the last part of urlParts.
urlParts[urlParts.length - 1];
Just grab the last element of the urlParts array:
var lastPart = urlParts[urlParts.length - 1];
Instead of $(location) why not just use location object and location.hash? Like this:
location.hash.replace('#/', '')
For url like http://www.url/name/something/#/venue it will give you venue.
You can get it like this:
var url = document.URL.split('#/')[1];
var currentUrl = $(location).attr('href');
var urlParts = currentUrl.split( "/" );
alert(urlParts[urlParts.length-1]);
The fiddle here.
To grab the last element in the array urlParts, just use:
var last = urlParts[urlParts.length-1];
As an alternate way to do this, you could do:
var last = currentUrl.substr( currentUrl.lastIndexOf("/")+1 );
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;
}