How to get the anchor from the URL using jQuery? - javascript

I have a URL that is like:
www.example.com/task1/1.3.html#a_1
How can I get the a_1 anchor value using jQuery and store it as a variable?

For current window, you can use this:
var hash = window.location.hash.substr(1);
To get the hash value of the main window, use this:
var hash = window.top.location.hash.substr(1);
If you have a string with an URL/hash, the easiest method is:
var url = 'https://www.stackoverflow.com/questions/123/abc#10076097';
var hash = url.split('#').pop();
If you're using jQuery, use this:
var hash = $(location).attr('hash');

You can use the .indexOf() and .substring(), like this:
var url = "www.aaa.com/task1/1.3.html#a_1";
var hash = url.substring(url.indexOf("#")+1);
You can give it a try here, if it may not have a # in it, do an if(url.indexOf("#") != -1) check like this:
var url = "www.aaa.com/task1/1.3.html#a_1", idx = url.indexOf("#");
var hash = idx != -1 ? url.substring(idx+1) : "";
If this is the current page URL, you can just use window.location.hash to get it, and replace the # if you wish.

Use
window.location.hash
to retrieve everything beyond and including the #

jQuery style:
$(location).attr('hash');

You can use the following "trick" to parse any valid URL. It takes advantage of the anchor element's special href-related property, hash.
With jQuery
function getHashFromUrl(url){
return $("<a />").attr("href", url)[0].hash.replace(/^#/, "");
}
getHashFromUrl("www.example.com/task1/1.3.html#a_1"); // a_1
With plain JS
function getHashFromUrl(url){
var a = document.createElement("a");
a.href = url;
return a.hash.replace(/^#/, "");
};
getHashFromUrl("www.example.com/task1/1.3.html#a_1"); // a_1

If you just have a plain url string (and therefore don't have a hash attribute) you can also use a regular expression:
var url = "www.example.com/task1/1.3.html#a_1"
var anchor = url.match(/#(.*)/)[1]

Related

How to get string after '#' in URL

I am trying to get the string available after # in the URL.
basically its an ID of the element that is passed from other page.
for example, the below url has investors_brand after # character, i need to get that string with jquery
www.example.com/about_us#company_branding
here is the code.
var a = window.location.href;
console.log(a.slice('#'));
But could not get it right.
Use split
console.log('www.example.com/about_us#company_branding'.split('#')[1])
var a = window.location.href;
console.log(a.split('#')[1]);
use window.location.hash
console.log(window.location.hash)
You could use substring.
const hash = window.location.hash;
console.log(hash.substring(1));
This returns the part of the string after the index 1
You can get the hash value:
window.location.hash
If you want it without the # use:
window.location.hash.substring(1)
Try
var a = 'abc.com/blog/seo-google-123';
console.log(a.split('-').pop());
Result: 123
You can use the hash value:
https://www.w3schools.com/jsref/prop_loc_hash.asp
var x = location.hash;

Replace the url parameter value using js

I have a URL like below.
something.com/TaskHandler/search.do?action=search&category=basic&page=1&sortBy=NAME&Ascending=true&showHiddenElements=false
I want to replace the value of parameter showHiddenElements to some new value.
for e.g. exising value in URL -> showHiddenElements=false
I want to change it through JavaScript to -> showHiddenElements=true
Please advise.
Edit:
showHiddenElements may not always be false. And In some cases it may not be available.
Use the URL Object:
const url = new URL('http://something.com/TaskHandler/search.do?action=search&category=basic&page=1&sortBy=NAME&Ascending=true&showHiddenElements=false');
url.searchParams.delete('showHiddenElements');
url.searchParams.append('showHiddenElements', true);
So you just delete the parameter and update it with the new one (not the most elegant)
Docs here: https://developer.mozilla.org/fr/docs/Web/API/URL
You could use String.replace for that:
var url = 'something.com/TaskHandler/search.do?action=search&category=basic&page=1&sortBy=NAME&Ascending=true&showHiddenElements=false';
newUrl = url.replace('showHiddenElements=false', 'showHiddenElements=true');
You could also do it fancy and use regex:
var url = 'something.com/TaskHandler/search.do?action=search&category=basic&page=1&sortBy=NAME&Ascending=true&showHiddenElements=false';
newUrl = url.replace(/showHiddenElements=false$/, 'showHiddenElements=true');
The regex would only match showHiddenElements=false if it's on the end of the URL
To see if it's available you could use regex too:
var url = 'something.com/TaskHandler/search.do?action=search&category=basic&page=1&sortBy=NAME&Ascending=true&showHiddenElements=false';
// If the url doesn't have a showHiddenElements=__any_word__
if (!url.match(/showHiddenElements=\w+/)) {
url = url + 'showHiddenElements=false';
}
var url = "something.com/TaskHandler/search.do?action=search&category=basic&page=1&sortBy=NAME&Ascending=true&showHiddenElements=false";
alert("Before: "+url);
url = url.replace("&showHiddenElements=false","&showHiddenElements=true");
alert("After: "+url);
//Console.log clips the end so we can't see the result :(
Maybe something liket this:
var loc = window.location.href;
var newLoc = loc.Replace('showHiddenElements=true', 'showHiddenElements=false')
A JavaScript Regular Expression should help if you are just treating the URL as a string.
var str = 'something.com/TaskHandler/search.do?action=search&category=basic&page=1&sortBy=NAME&Ascending=true&showHiddenElements=false';
var res = str.replace(/showHiddenElements/i, 'true');
console.log(res);

Remove hash from current page’s URL

I want to remove the hash, as well as anything after it, from a URL. For example, I might have:
http://example.com/#question_1
… which slides to question no. 1 to show an error message. When the user’s input then passes validation, I need to remove #question_1 from the current location.
I’ve tried all of these, but none of them has worked for me:
document.location.href.replace(location.hash, "");
window.location.hash.split('#')[0];
window.location.hash.substr(0, window.location.hash.indexOf('#'));
Note: I don’t just want to get the URL – I want to remove it from my address bar.
history.pushState("", document.title, window.location.href.replace(/\#(.+)/, '').replace(/http(s?)\:\/\/([^\/]+)/, '') )
Try this :use .split() to split string by # and then read first element in array using index 0
var url = 'http://example.com#question_1';
var urlWithoutHash = url.split('#')[0];
alert(urlWithoutHash );
Use split in javascript
var str = "http://example.com#question_1";
alert(str.split("#")[0]);
Try this way:
var currentPath = window.location.pathname;
var myUrl = currentPath.split("#")[0];
OR
var currentPath = window.location.href;
var myUrl = currentPath.split("#")[0];
Hope it helps.
This will clear the id selector from the uri
location.hash = '';
Use .split as shown :
var str = "http://example.com#question_1";
alert((str.split("#")[0]);
or use .substring() as shown :
var str = "http://example.com#question_1";
alert((str.substring(0,str.indexOf('#'))));

How do i match text after a specific character?

I have a url that looks like this:
http://mysite/#/12345
How do I retrieve the text using regex after the /#/ which is essentially a token that I would like to use elsewhere in my javascript application?
Thanks.
You don't need regex here, just String#substr using String#indexOf:
var s = 'http://mysite/#/12345';
var p ='/#/'; // search needle
var r= s.substr(s.indexOf(p) + p.length);
//=> 12345
Let the browser do it for you
var parser = document.createElement('a');
parser.href = "http://mysite/#/12345";
alert(parser.hash.substring(2)); //This is just to remove the #/ at the start of the string
JSFiddle: http://jsfiddle.net/gibble/uvhqa4yv/
Try with JavaScript String methods.
var str='http://mysite/#/12345';
alert(str.substring(str.lastIndexOf("/#/")+3));
You can try with String'smatch() method as well that uses regex expression.
Just get the matched group from index 1 that is captured by enclosing inside the parenthesis (...)
var str='http://mysite/#/12345';
alert(str.match(/\/#\/(.*)$/)[1]);
Using the browser to parse the URL and getting the hash would probably be most reliable and would work with any valid URL
var url = 'http://mysite/#/12345';
var ele = document.createElement('a');
ele.href = url;
var result = ele.hash.slice(2);
FIDDLE
or you can just split and pop it
var result = url.split('#/').pop();

FileName from url excluding querystring

I have a url :
http://www.xyz.com/a/test.jsp?a=b&c=d
How do I get test.jsp of it ?
This should do it:
var path = document.location.pathname,
file = path.substr(path.lastIndexOf('/'));
Reference: document.location, substr, lastIndexOf
I wont just show you the answer, but I'll give you direction to it. First... strip out everything after the "?" by using a string utility and location.href.status (that will give you the querystring). Then what you will be left with will be the URL; get everything after the last "/" (hint: lastindexof).
Use a regular expression.
var urlVal = 'http://www.xyz.com/a/test.jsp?a=b&c=d';
var result = /a\/(.*)\?/.exec(urlVal)[1]
the regex returns an array, use [1] to get the test.jsp
This method does not depend on pathname:
<script>
var url = 'http://www.xyz.com/a/test.jsp?a=b&c=d';
var file_with_parameters = url.substr(url.lastIndexOf('/') + 1);
var file = file_with_parameters.substr(0, file_with_parameters.lastIndexOf('?'));
// file now contains "test.jsp"
</script>
var your_link = "http://www.xyz.com/a/test.jsp?a=b&c=d";
// strip the query from the link
your_link = your_link.split("?");
your_link = your_link[0];
// get the the test.jsp or whatever is there
var the_part_you_want = your_link.substring(your_link.lastIndexOf("/")+1);
Try this:
/\/([^/]+)$/.exec(window.location.pathname)[1]

Categories

Resources