How to reset a value in javascript function - javascript

I have an url like :
?from=353&distance=&page=2
If I clik on a map’s track, I add or reset track to a new value. In the same time I would like to reset the page's value to zéro
function processTrackGeoJSON(feature, layer) {
layer.on("click", () => {
let search = window.location.search;
if(search.includes("track")) {
search = search.replace(/track=\d+/g, 'track=' + feature.properties.id);
}
else {
search += (search.length === 0 ? '?' : '')+'&track='+feature.properties.id;
}
window.location = window.location.pathname + search;
})
}
I'm trying to chaining, but ther don't work :
search.replace(/track=\d+/g, 'track=' + feature.properties.id).replace(/page=\d+/g, 'track=' + 0)
For example, I have an url like :
http://example.com?name=paris&from=353&distance&page=2
After on(click) I get a value like track=37
I would like to add this value and reset the page's value to 0 (or delete it) like
http://example.com?name=paris&from=353&distance=120&trak=37&page=0
or
http://example.com?name=paris&from=353&distance=120&trak=37

I think this will be the better way, check this one. You can use URLSearchParams
const query = '?from=353&distance=&page=2'
const searchParams = new URLSearchParams(query);
const parameterExist = searchParams.get('page');
if(parameterExist){
searchParams.set('page', 1) // with your feature.properties.id
}else{
searchParams.set('page', 0) // default value
}
window.history.replaceState({}, '', `${window.location.pathname}?${searchParams}`);
Update to the question
const url = new URL('http://example.com?name=paris&from=353&distance=120&page=2')
const clickedTrackValue = 37;
const params = new URLSearchParams(url.search);
params.append('track', clickedTrackValue);
params.delete('page') // searchParams.set('page', 0)
console.log(`${url.origin}?${params}`)
// for updating the new url, use the below snippet
//window.history.replaceState({}, '', `${location.pathname}?${params}`);

Related

React JS - Map Function - Accessing Local Variable

I have a Dropdown and Search Box (based on the dropdown menu, the searchbox fetches results from respective JSON files)
function onSearch({ currentTarget }) {
var i = document.getElementById("SearchBox")
if (i.value == 1) {
const results = fuse.search(query);
const RequestResults = results ? results.map(data => data.item) : global;
const srResults = RequestResults.slice(0, limit)
console.table(srResults)
updateQuery(currentTarget.value);
}
else if (i.value == 2) {
const eucresults = eucfuse.search(query);
const RequestResults = eucresults ? eucresults.map(data => data.item) : euc;
const srResults = RequestResults.slice(0, limit)
console.table(srResults)
updateQuery(currentTarget.value);
}
}
When I try to fetch the results in a component, I get srResults as undefined as they are local.
{srResults.map(data => {
const { name, link } = data;
return (
<p ><small>{name}</small></p>
)
})}
I am new to React and can anyone help me in fixing this. I have tried using Jquery.append and I dont want use it.

Change button HREF depending on the address bar URL

I have a website that users with an affiliate URL often visit, for example:
https://demowebsite.com/?ref=550
There is a link that initially has an URL:
https://demowebsite.com/register
Register
How can I make that if there is a part with a ref ID in the address bar like https://demowebsite.com/?ref=550, then the href is transformed into the following by click:
https://subdomain.demowebsite.com/ref/
and add the ref ID at the end as an append:
https://subdomain.demowebsite.com/ref/550
And if there is no affiliate part in the address bar, then the link would remain the same.
Register
I would be grateful for any help.
You can use the location object given in tabs
<script>
var href=location.href
if(href.includes('ref')){
document.getElementById('reg')
.href="https://demowebsite.com/ref/" + href.split('=')[1]
}
</script>
Use the URL api
const affRef = (loc) => {
const url = new URL(loc || location.href); // we can pass a url to test
const ref = url.searchParams.get("ref");
if (ref) {
url.pathname += ref;
url.searchParams.delete("ref")
url.hostname = "subdomain."+url.hostname;
}
return url.href
};
document.getElementById("reg1").href = affRef("https://demowebsite.com/register"); // nothing should happen
document.getElementById("reg2").href = affRef("https://demowebsite.com/?ref=550"); // changed
1. Register<br/>
2. Register
On your site you would not need the LOC or pass the URL
const affRef = () => {
const url = new URL(location.href);
const ref = url.searchParams.get("ref");
if (ref) {
url.pathname += ref;
url.searchParams.delete("ref")
url.hostname = "subdomain."+url.hostname;
}
return url.href
};
document.getElementById("reg1").href = affRef();
1. Register<br/>
2. Register
You can change it from the place where the users are being sent. I'm not very sure, but the code would look something like this:
var searchBar; //Assign the Search bar it's value through ID or however you can
if (searchBar=="www.demowebsite.com/register") {
document.getElementById("a").href = ""; //Your desired link
}
else {
document.getElementById("a").href = ""; //Your desired link
}
Register

RegEx that match react router path declaration

I have a map of routes with react router path as keys, eg:
const routes = [
{
page: "mySettings",
label: "pages.mySettings",
path: "/professionels/mes-reglages.html",
exact: true
},
{
page: "viewUser",
label: "pages.viewUser",
path: "/users/:id/view.html",
exact: true
}
];
I want from a location retrieved with useHistory().location.pathname, to match all the path that match the key in react-router terms, eg:
(pathname) => get(routesMap, "/professionels/mes-reglages.html") => should match routesMap.get('/professionels/mes-reglages.html')
(pathname) => get(routesMap, "/users/11/view.html") => should match routesMap.get('/users/:id/view.html')
and all react-router paths so this should work too:
(pathname) => get(routesMap, "/users/11/settings/10/items/24/view.html") => should match routesMap.get('/users/:userId/settings/:settingId/items/:id/view.html')
I have started here, any idea how I can do that with a regexp?
https://codesandbox.io/s/youthful-wing-fjgm1
Based on your comments i adjusted the code a bit and wrote a rapper function for your lookup.
The following rules you have to watch out for when creating the urls:
The last id always gets replaced by {id}
All other ids get replaced by url part to id without plural and "Id" attached ("/users/111" -> "/users/{userId}")
This would be the function:
const getRouteFromPath = (map, url) => {
if (url.match(/\/\d+\//g).length > 1) {
let allowedUrlPart = getAllowedIdQualifier(map);
let urlParts = url.match(/(?<=\/)\w+(?=\/\d+\/)/g);
urlParts.forEach(val => {
if (!allowedUrlPart.includes(val)) {
urlParts = urlParts.slice(urlParts.indexOf(val), 1);
}
});
urlParts.forEach((val, key, arr) => {
if (key === arr.length - 1) {
let regex = new RegExp("(?<=/" + val + "/)\\d+", "g");
let replacement = ":id";
url = url.replace(regex, replacement);
} else {
let regex = new RegExp("(?<=/" + val + "/)\\d+", "g");
let replacement = ":" + val.slice(0, -1) + "Id";
url = url.replace(regex, replacement);
}
});
return map.get(url);
} else {
url = url.replace(/\/\d+\//g, "/:id/");
return map.get(url);
}
};
const getAllowedIdQualifier = map => {
let allowedQualifiers = [];
map.forEach(val => {
let allowed = val.path.match(/(?<=\/)\w+(?=\/:)/g);
allowed.forEach(e => {
if (!allowedQualifiers.includes(e)) {
allowedQualifiers.push(e);
}
});
});
return allowedQualifiers;
};
export default getRouteFromPath;
As parameter you pass in the url to match as first parameter and the map of routes as the second paramter and call the function getRoute() instead of the direct map.get() call you where using before.
Here is the example with the urls adjusted to follow the rules, since you need some rules to be able to apply RegEx.
EDIT:
I adjusted the script, so that it reads the map first and determines the allowed paths which accept a id and then check the possible ids from an actual url against it.
https://codesandbox.io/s/kind-moon-9oyj9?fontsize=14&hidenavigation=1&theme=dark

How to preserve applied filters on browser back button in react js

In my application, there are filters on all list pages.
Now as per requirement, I want to preserve applied filters on browser back button.
E.g say user has applied filters on sales list page.
After that he clicks on one record to go to sales edit page.
Now if user hit browser back button then those applied filters should remain.
To accomplish this i did like below.
On sales list page ,
componentWillMount() {
const { list, checkReportClose,
updateReportCloseStatus } = this.props;
const { inPopState } = this.state;
window.onpopstate = () => {
if (!_.isEmpty(list)) {
this.setState({ filters: JSON.parse(list.input.filters),
inPopState: true}, this.loadList);
}
}
if(!inPopState && inPopState != undefined &&
checkReportClose == false) {
this.loadList();
}
}
Using above code it works fine but while back button it calls the lis page api (this.loadList) twise.
Please suggest some new solution or modification in existing one.
Thanks.
I would suggest using the url to store filters as parameters.
I've written an example below. Let's use http://skylerfenn.com/news?order=asc&category=feature&year=2017 as the url for the functions below.
Step 1: Call getParameters() in the window.onpopstate and store the parameters in state. Using the URL above, getParameters() will return the parameters as the object { order: 'asc', category: 'feature', year: '2017' }.
function getParameters() {
let parameters = window.location.search.replace('?', '');
let currentParameters = {};
if (Object.keys(parameters).length) {
parameters = parameters.split('&');
for (let i = 0; i < parameters.length; i++) {
let parameter = parameters[i].split('=');
currentParameters[parameter[0]] = parameter[1];
}
}
return currentParameters;
}
Step 2: Pass any new parameters to the getNewParameters function below as an object. For example, calling getNewParameters({ order: 'desc', year: null }) returns the object { order: 'desc', category: 'feature' }. Notice that it removes year since it's null.
function getNewParameters(newParameters) {
const parameters = getParameters();
const keys = Object.keys(newParameters);
for (let i = 0; i < keys.length; i++) {
const value = newParameters[keys[i]];
parameters[keys[i]] = value;
if (!value) {
delete parameters[keys[i]];
}
}
return parameters;
}
Step 3: Use the result from getNewParameters to update state. Also pass the result to function below to update your url.
updateUrl(parameters) {
let search = '';
let j = 0;
let separator = '?';
Object.keys(parameters).forEach((key) => {
let value = parameters[key];
if (value) {
if (j !== 0) {
separator = '&';
}
search += `${separator}${key}=${value}`;
j++;
}
});
let newUrl = `${location.origin}${location.pathname}${search}`;
// prevents pushing same url if function won't change url.
if (location.href !== newUrl) {
history.pushState(null, null, newUrl);
}
}

How to properly add search query param to url containing hash in javascript?

I want to add a base url and query parameters to each link:
function buildURL(relativePath) {
var url = new URL('http://example.com/' + relativePath);
url.searchParams.set('utm_source', 'app');
return url.toString();
}
It works fine for most cases:
buildURL('search')
"http://example.com/search?utm_source=app"
buildURL('search?q=query&page=2')
"http://example.com/search?q=query&page=2&utm_source=app"
The problem starts when I add an anchor:
buildURL('search#anchor')
"http://example.com/search?utm_source=app#anchor"
buildURL('search#anchor?q=query')
"http://example.com/search?utm_source=app#anchor?q=query"
This is not a valid URL with an anchor.
Any ideas on how to overcome that using URL?
EDIT
The expected outcome is adding the query params after the anchor
buildURL('search#anchor')
"http://example.com/search#anchor?utm_source=app"
buildURL('search#anchor?q=query')
"http://example.com/search#anchor?utm_source=app?q=query"
function buildURL(relativePath) {
var url = new URL('http://example.com/' + relativePath);
url.searchParams.set('utm_source', 'app');
return url.toString();
}
console.log(buildURL("search"));
console.log(buildURL("search?q=query&page=1"));
console.log(buildURL("search#anchor"));
console.log(buildURL("search#anchor?q=query"));
Don't pass in a hash in the search params.
But if you must, you can detect the hash, split it from the parameter, set the search param and add the hash
function buildURL(relativePath) {
var hash = "";
if (relativePath.indexOf("#")!=-1) {
var parts = relativePath.split("#");
hash = encodeURIComponent(parts[1]); // optionally handle ? in the hash part
relativePath=parts[0];
}
var url = new URL('http://example.com/' + relativePath);
url.searchParams.set('utm_source', 'app');
if (hash) url.hash=hash;
return url.toString();
}
console.log(buildURL("search"));
console.log(buildURL("search?q=query&page=1"));
console.log(buildURL("search#anchor"));
console.log(buildURL("search#anchor?q=query"));
This should work.. Pass the hash after the query params
function buildURL(path) {
var relativePath = path.split('#')
var url = new URL('http://example.com/' + relativePath[0]);
url.searchParams.set('utm_source', 'app');
url.hash = relativePath[1] ? relativePath[1] : ''
return url.toString();
}
console.log(buildURL("search"));
console.log(buildURL("search?q=query&page=1"));
console.log(buildURL("search#anchor"));
console.log(buildURL("search#anchor?q=query"));
console.log(buildURL("searchr?q=query&q2=query2#anchor"));

Categories