I'm using React and I'm trying to handle duplicate forward slashes on my website similar to Facebook. Its works like this:
If the user acess: https://facebook.com///settings the url is updated to https://facebook.com/settings
I'm trying to do this overriding the window.location.pathname like this:
const pattern = /\/+[/]/;
const urlFinal = window.location.pathname.replace(pattern, "");
window.location.pathname = urlFinal;
But it returns an infinite loop of refresh on the window.
So, how can I do that? Someone can help me?
You need to leave a slash:
let pathName = window.location.pathname;
const pattern = /\/+[/]/;
const urlFinal = pathname.replace(pattern, "/");
if (urlFinal.length < pathName) window.location.pathname = urlFinal;
Related
Check this image
I have this link in (note this link not from search URL)
var link = https://google.com/?ib=10 in main.js file.
Now how to get that 10 from this link in javaScript on Page load
I have tried this way
var link1 = link;
const url3 = new URLSearchParams(link1);
const ur = url3.get("ib");
var finaltgid = ur;
alert(ur);
But its not working may be this code only work when we use window.location.search
Instead of var or const
urlsearchparams does not parse full url, you need to pass only query part, like this:
var link = 'https://google.com/?ib=10';
const url = new URLSearchParams(new URL(link).search);
const ib = url.get("ib");
console.log(ib);
URLSearchParams only accepts the actual query part in the constructor. You are including the full link.
Edit: For a given link you can just supply the link in place of document.location (which directly fetches the pages current location)
Considering this as Vanilla JS. You can do the following.
let params = (new URL(document.location)).searchParams;
let ib = parseInt(params.get('ib')); // is the number 10
Note, using the parseInt to get the value as a number.
I searched for the answer to my question and even tried some solutions, but wasn't able to get anything to really work. I'm newish to javascript, so that might also be why.
I have a specific URL and whenever someone goes to that URL, I want to add parameters to it, but only if no parameters are already present. Parameters get added to the URL for other on click events, but on page load, I need a set of parameters added to the URL.
I tried to use the history API and I think I'm kind of close, but I'm not able to get it to do what I want it to do.
function addDefaultParam(url) {
var currentURL = window.location.href; //get the current url
var baseURL = '/our-partners'; //this is the url that should have params added
var paramString = '?asc=true&sortBy=display_name'; //here are the params
if (currentURL === baseURL) {
window.history.pushState("object or string", "Title", "/" + paramString);
}
return url;
}
I'm using basic js in this because that's what was used in the other functions (I inherited this code). Any help would be greatly appreciated.
You can register the addDefaultParam function to fire when the document first loads in the browser and use the Location interface to check the state of the current path and query string of the URL and if they match your conditions, update the current query string value.
See below for an example:
window.addEventListener("load", addDefaultParam);
function addDefaultParam() {
let currentPath = document.location.pathname;
let currentQueryString = document.location.search;
let targetPath = "/our-partners";
if (currentPath === targetPath && !currentQueryString) {
document.location.search = "?asc=true&sortBy=display_name";
}
}
Well, on my site I have a FAQ where users can access specific questions through the URL, such that:
https://example.com/faq#question-1
And for this I use Jquery, such that:
if (window.location.hash) {
$(window.location.hash).open();
}
But I want that if the user enters more than one hash in the URL such that:
https://example.com/faq#question-1#question-2#question-3#question-n
All hashes are removed from the URL except the first #question-1
How can I do this?
Edit:
if user type https://example.com/faq#question-1#question-2#question-3#question-n then change the url to https://example.com/faq#question-1 so that only the first hash appears in the url and the FAQ only has to read a single hash.
It could something as simple as
var hash = window.location.hash;
var filtered_hash = '';
if(hash.length > 0){
filtered_hash = '#' + hash.split("#")[1];
window.location.hash = filtered_hash;
}
console.log(filtered_hash);
This should work for you
var str="https://example.com/faq#question-1#question-2#question-3#question-n";
var trimmedStr = str.split("#").slice(0,2).join("#");
console.log(trimmedStr);
This removes all hashes after the first hash.
You can use something like -
location.hash = '#'+location.hash.split('#')[1]
I have a constant link looking like this:
http://link.com/?val1=val1&val2=val2
And this link redirects me to a new link with a random value of a constant param such like;
http://link2.com/?constant=randomvalue/
Each time I use the first link, I get a random value from the following link.
By using Node.js, how can I catch the 'randomvalue' of 'constant' in the second link?
I have to use the first link to reach the second one.
Try reading the second link as a URL
let secondURL = new URL("http://link2.com/?constant=randomvalue/");
Then extract the value of the constant searchparam like so
let constantValue = secondURL.searchParams.get("constant"); //"randomvalue/"
#Misantorp's answer is probably best, but there is another way to do it. Check out the querystring module built into Node, it has a convenient parse method just for things like this: https://nodejs.org/api/querystring.html
This should work:
const querystring = require('querystring');
querystring.parse("http://link2.com/?constant=randomvalue/"); // { 'http://link2.com/?constant': 'randomvalue/' }
You may want to substring from the ? onwards to make it more clear:
const str = "http://link2.com/?constant=randomvalue/";
const paramIndex = str.indexOf("?");
if (paramIndex >= 0) {
const queryParamStr = str.substr(str.indexOf("?"));
const queryParams = querystring.parse(queryParamStr);
console.log(queryParams["constant"]);
}
I am trying to get hostname from set of urls that my webapp can encounter with.
The desired output should be something like http://localhost/Webapp/, ending at /Webapp/ and everything after that should be removed.
Kindly note that I dont want to use word Webapp in regex as this name is dynamic and used for demo/testcase only.this can be anything , not harcoded.
In real example I am using location.href.replace(/index.+/g, "").replace(/#.+/g, "")
and I want to keep only hostname ending atWebapp/.
Problem:
my solution seems to working fine except "http://localhost/Webapp/#" is not working correctly ? why is that ? see fiddle below
JSFIDDLE: http://jsfiddle.net/bababalcksheep/um0uqb8v/
JS:
var getHost = function (url) {
return url.replace(/index.+/g, "").replace(/#.+/g, "")
};
var urls = [
"http://localhost/Webapp/",
"http://localhost/Webapp/#",
"http://localhost:8080/Webapp/#sdf#dfgdf#fdg",
"12.168.1.1:8080/Webapp/index.html#",
"https://localhost/Webapp/index.html#ab#bg",
"https://localhost/Webapp/index.html"
];
//Print all urls
$.each(urls, function () {
$("<p/>").text(getHost(this)).appendTo($(".test"));
});
Use url.match(/https?:\/\/([^\/]+)/);
EDIT:
It returns an array where the 1st element is the host with protocol and the 2nd without.
You can try removing anything after the last slash (files and hash-es):
var getHost = function (url) {
return url.replace(/\/[^/]*?$/, '/');
};
And here's the updated fiddle.
There's a bit of a trick you can use to get the browser to extract the hostname for you.
var getHost = function (url) {
var a = document.createElement('a');
a.href = url;
return a.hostname;
};
It also appears you want the path as well. You can access it with the pathname property of the a element. If you're doing that, you ought to rename the function to something like getHostAndPath().