Removing hash from URL using JS/jQuery - javascript

I have the following code:
if(window.location.hash){
var hash = window.location.hash.substring(1);
}
var hash = window.location.hash.substring(1);
if(hash.length > 0 && hash.search('^y([0-9]+)g([0-9]+)$') >= 0)
{
$('#recs').removeClass('closed');
$('#rec_select_year').val(hash.match('y([0-9]+)')[1]);
$('#rec_g_select').val(hash.match('g([0-9]+)')[1]);
$('html, body').animate({
scrollTop: $('#docs').offset().top + 200
}, 0);
changeDocuments();
}
else
{
changeDocuments();
}
$('.filter').change(function() {
updateDocumentList();
var years = $('#rec_select_year').val();
var groups = $('#rec_g_select').val();
hash = 'y' + years + 'g' + groups;
});
I'm having difficulties with removing hash from URL. I need to change url to this http://codify.org/group/y2018g7
For that reason, I used substring() method to remove the hash, however it affects to the url and it changes to http://codify.org/group/, which basically removes the end of URL ../y2018g7
How can I change hash to to display an URL which is http://codify.org/group/y2018g7 ?

Use RegExp to replace # from url like below.
var url = "codify.org/group/#y2018g7";
var regx = "/#/g";
var newUrl= url.replace(eval(regx), '');
console.log(newUrl);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Note: In above RegExp The g modifier is for global match (find all matches rather than stopping after the first match)

This will work if you want to replace all the hash with an empty string.
window.location.href.split("#").join('')

Related

Get substring from between two identical characters in a URL

How would I extract just the number from between the two slashes in this URL:
https://myDomain.sharepoint.com/sites/MySite/SitePages/MyPage.aspx?/id=612/&CT=1223336827303&OR=OWA-NT&CID=7f71df69-6cef-fd22-82d9-5823a32895f9
I only want the number (612 in this case but can be different no. and can vary in length) and nothing else.
The code I've attempted:
if(window.location.href.indexOf("id=") > -1){
var url = window.location.href;
console.log(url, 'url');
var findUrl = window.location.search;
console.log(findUrl, 'findUrl');
var url2 = url.substring(url.indexOf("=") + 1);
console.log(url2, 'url2');
var url3 = url.substring(
url.lastIndexOf("/") + 1,
url.lastIndexOf("/")
);
var url4 = url.split('/').pop().split('/')[0];
console.log(url3, 'url3');
console.log(url4, 'url4');
this.setState({
Id: url4,
filterValue: url4
}, () => {
this._editItemUrl();
});
}
I've read:
How do you use a variable in a regular expression?
JavaScript - Use variable in string match
get string between two strings with javascript
Buy none answer my specific question.
your problem is the forward slashes in the query-parameter string. If you can remove those (str replace) you can use JS's URLSearchParams.
see: https://www.sitepoint.com/get-url-parameters-with-javascript/

Removing Url and Include Id using Regex and Jquery

I am new to Regex and my question is how can i include the ID from the url and remove it using Regex? because as of now , It only removes the actionMe=reload&Id= but the Id still return so after removing it and replacing with new Url, the old id is still included plus the new ID,
Example, Before removing and replacing the Url:
http://localhost:2216/Main/WorkerPage?workerId=10&actionMe=reload&Id=15
And After Removing and replacing the url , it goes like this:
http://localhost:2216/Main/WorkerPage?workerId=10&actionMe=reload&Id=1615
This is my Code Snippet:
var sss = $("#Id").val();
if (window.location.href.indexOf("&actionMe=reload&Id=") > -1) {
var regex = /(\&|&)actionMe=reload&Id=/;
var location = window.location.href;
if (regex.test(location)) {
window.location = location.replace(regex, "&actionMe=reload&Id=" + sss)
}
}
Thanks for Answering guys:)
you can use this code to update url parameters
function updateQueryStringParameter(uri, key, value) {
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
var separator = uri.indexOf('?') !== -1 ? "&" : "?";
if (uri.match(re)) {
return uri.replace(re, '$1' + key + "=" + value + '$2');
}
else {
return uri + separator + key + "=" + value;
}
}
I got it here
Now, in your case, you can use it like this
var url = window.location.href;
var sss = $("#Id").val();
var newUrl = updateQueryStringParameter(url, "id", sss);
//do whatever you want to newUrl
//to redirect to new url
window.location = newUrl;
Pretty sure all you need is /&Id=\d+/ as your RegExp. Don't need to select any of actionMe=reload unless you need that for specification (in that case, just add it back). The rest of your code works as intended, just your regex not selecting the precise part you were wanting.
Explanation:
The (\&|&) part of your regex is redundant, as & does not need to be escaped to work. As a matter of fact, since it's in parenthesis, you would end up capturing that & character, if you REALLY need that part, try (?:\&|&) to ignore the capture group. Your code replaced the matched regex, but did not include the number "15" after Id=, which is why it appended 15 after your edited version due to it not being matched and therefore not being replaced. Adding \d+ will select any trailing digits. This should give you the result you wanted.

Regex for URL with querystring

I use the following javascript with regex to test url string.
var url = window.location.pathname;
// create regexp to match current url pathname and remove trailing slash if
// present as it could collide with the link in navigation in case
// trailing slash wasn't present there
urlRegExp = new RegExp(url == '/' ? window.location.origin + '/?$' : url.replace(/\/$/, ''));
// now grab every link from the navigation
$('.page-sidebar a').each(function () {
// and test its normalized href against the url pathname regexp
if (urlRegExp.test(this.href.replace(/\/$/, ''))) {
$(this).closest("li").addClass("active");
}
});
But this regex doesnt include the querystring. How can I do that?
Perhaps you could match a string with something like this and construct from it what you want.
var rx = new RegExp("^(?:([^:\\/?#]+):)?(?:\\/\\/((?:(([^:#]*)(?::([^:#]*))?)?#)?([^:\\/?#]*)(?::(\\d*))?))?((((?:[^?#\\/]*\\/)*)([^?#]*))(?:\\?([^#]*))?(?:#(.*))?)");
var url = "http://stackoverflow.com/questions/16053753/regex-for-url-with-querystring?a0b&c=d&e=f#anchor";
var val = url.match(rx);
val.forEach(function (part) {
var result = $("#result");
var $text = $("<p>").text(part);
result.append($text);
});
You can play with this code on jsfiddle

Get URL Path without last segment

How can I get the URL Path of the current site, but without the last segment:
http://www.domain.com/first/second/last
I only need http://www.domain.com/first/second … with jQuery (or only JavaScript)
Using pop and URL api
this assumes the URL is not likely to change
I use document.URL since that is what is recommended
const url = new URL("https://www.example.com/first/second/last"); // new URL(document.URL)
let path = url.pathname.split("/");
path.pop(); // remove the last
url.pathname = path.join("/")
console.log(url)
Older answers: As requested by OP - with changes from comment
const url = "http://www.example.com/first/second/last", // document.URL,
shortUrl=url.substring(0,url.lastIndexOf("/"));
console.log(shortUrl)
Here is an alternative
const url = new URL("http://www.example.com/first/second/last"),
shortUrl = `${url.protocol}//${url.hostname}${url.pathname.slice(0,url.pathname.lastIndexOf("/"))}`
console.log(shortUrl)
http://jsfiddle.net/KZsEW
Try the following for all browsers:
var url = "http://www.domain.com/first/second/last"; // or var url = document.URL;
var subUrl = url.substring(0,url.lastIndexOf("/"))
alert(subUrl);
​
The lastIndexOf() method returns the position of the last occurrence of a specified value in a string.
Note: The string is searched from the end to the beginning, but
returns the index starting at the beginning, at postion 0.
This method returns -1 if the value to search for never occurs.
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/lastIndexOf
Try this:
var url = 'http://www.domain.com/first/second/last';
for(var i=url.length-1; i>=0;i--){
if(url[i]!='/'){
url= url.substr(0,i);
}
else{
alert(url);
break;
}
}
I'm not sure this is the most elegant of solutions, but you just want the substring up to the last slash, or second to last if the last character is a slash. Here I first take the part of the URL that appears after the protocol (http:// or https://) so that on for example http://stackoverflow.com it returns http://stackoverflow.com.
var url = document.URL.split('://');
var last_slash;
var result;
if (url[1].charAt(url[1].length - 1) === '/') {
url[1] = url[1].substring(0, url[1].length - 1);
}
last_slash = url[1].lastIndexOf('/');
result = url[0] + '://' + ((last_slash !== -1) ? url[1].substring(0, last_slash) : url[1]);
edit: jsfiddle http://jsfiddle.net/CV6d4/

How to grab the last bit of a url before the "?" in JavaScript?

I'm using this to grab the last part of the url:
url = window.location.href;
parts = url.split("/");
if (parts[parts.length-1].length == 0) {
lastBit = parts[parts.length-2];
} else {
lastBit = parts[parts.length-1];
}
The above works with or without a forward slash. So if my url was:
http://mysite.com/path/to/welcome/
I would get just this:
welcome
But what if my url is:
http://mysite.com/path/to/welcome/?foo=bar&hello=bye
How can I still get "welcome" and disregard everything that comes after it?
How about
var urlWithoutSearch = location.href.replace(location.search, '');
Just use location.pathname:
var parts = window.location.pathname.replace(/\/$/, '').split('/'),
lastBit = parts[parts.length - 1];
The replace() gets rid of a trailing / character, if present. (We don't care about a leading / in this case.)
Ex.
> '/path/to/welcome/'.replace(/\/$/, '').split('/')
> ["", "path", "to", "welcome"]
Look at window.location.pathname and work with this. This variable just includes the path and does not include any query parameters. So in your example you would be left with /path/to/welcome and parsing that is trivial.
lastBit = window.location.pathname.match(/\/([^\/]+?)\/(?:\?|$)/i)[1];
Do a split on ? before.
url = window.location.href;
urlParts = url.split('?');
parts = urlParts[0].split("/");
if (parts[parts.length-1].length == 0) {
lastBit = parts[parts.length-2];
} else {
lastBit = parts[parts.length-1];
}
First remove the query-string by:
url = window.location.href.replace(window.location.search, "");

Categories

Resources