I would like to match on a specific query parameter if it is in the URL. I pasted the query param directly into the isMatch but I don't think this is how to properly set it up:
isMatch: () => isInURL("search?q=", { usePathName: true }),
Do I have to structure the param differently? I assume so but I'm not familiar how since I am new to javascript.
Your current implementation checks for a hardcoded string "search?q=" in the URL path name, which is not ideal if you want to match on different query parameters.
To match on a specific query parameter, you can extract the value of that parameter from the URL using JavaScript's URLSearchParams API. Here's an updated example:
isMatch: () => {
const urlParams = new URLSearchParams(window.location.search);
const paramValue = urlParams.get("q");
return paramValue !== null;
},
In this example, window.location.search returns the query string of the current URL, which is then passed to URLSearchParams to extract the value of the "q" parameter. The function returns true if the parameter is present in the URL and false otherwise.
EDIT 1
You can check if the query parameter is attached to "search" in the URL by checking the pathname property of the window.location object, like this:
isMatch: () => {
const urlParams = new URLSearchParams(window.location.search);
const paramValue = urlParams.get("q");
return paramValue !== null && window.location.pathname === "/search";
},
Related
I am trying to change a url param to object?
const url = key=hhdfghh&num=123
const params = Object.fromEntries(new URLSearchParams(url));
console.log(params);
params.num = '123'
But i want it to be 123 type int
Some state
const [submittedSev, setSubmittedSev] = useState('');
const [newSev, setNewSev] = useState('');
Mixpanel events where I'm sending properties that may or may not exist. Sometimes the submittedSev and newSev may be empty strings but this will still send
mixpanel.track('COMPLETED', {
response: props.details.title,
submittedSev,
newSev
});
I'd like to only add submittedSev and newSev properties if the string isn't empty. For sure I could set up a conditional statement and check the string length and send a different Mixpanel event but that doesn't seem succinct enough.
Output of data that sometimes gets sent
{
"response": "hello",
"submittedSev": "",
"newSev": ""
}
How can I only add properties to object if they are not empty strings?
Here's a really concise way to do it using the spread ... operator and evaluating an expression with the AND operator && which returns the second value if the first is truthy:
// Example.js
const name = ''
const email = 'asd#gmail.com'
const phone = ''
const output = {
...(name && {name}),
...(email && {email}),
...(phone && {phone})
}
console.log(output)
So for your code it'd be:
mixpanel.track('COMPLETED', {
response: props.details.title,
...(submittedSev && {submittedSev}),
...(newSev && {newSev})
});
You could centralize the logic that sends the events in a separate function, and go through the properties of the event object and filter out the ones that are not empty strings:
function trackMixpanelEvent(eventType, event) {
const keys = Object.keys(event).filter(
key => Object.prototype.hasOwnProperty.call(event, key));
keys.forEach(key => {
if (event[key] === '') {
delete event[key];
}
});
mixpanel.track(eventType, event);
}
And then just call it without worrying which properties are empty strings:
trackMixpanelEvent('COMPLETED', {
response: props.details.title,
submittedSev,
newSev
});
I have following function that checks if url ends with any of the values in array instead I want to check if url contains any of the value in array.
If url contain any value in array function should return true else false.
var hasUrlCacheExcludeMatch = function(url) {
var cacheExcludeUrls = [
'/u/register',
'/i/new',
'/login'
];
return cacheExcludeUrls.some(path => url.endsWith(path));
}
Let me clear, I want to check if any value in array is substring of url.
I was wondering if it is possible to get the url parameter as JSON object using window object.
For ex. I have the url "/#/health?firstName=tom&secondName=Mike"
and get the value as {"firstName": "tom", "secondName": "Mike"}
I tried to explore the window object but could not find any help.
I think I can try parsing the string firstName=tom&secondName=Mike and convert this to json but this doesn't look like a great approach. BTW if there are smart way to parse, that too will be appreciated.
Please let me know if I should provide any more information.
In Angular you can get the URL with:
this.router.url
Once you've got the URL, you should use the very popular (14 mill downloads a week) npm qs module:
var qs = require('qs');
var obj = qs.parse('firstName=tom&secondName=Mike');
returns:
{
firstName: 'tom'
secondName: 'mike'
}
Using straight javascript first get the params and then convert them into an object:
<script type="text/javascript">
// params will be an object with key value pairs based on the url query string
var params = paramsToObject();
console.log(params);
// Get the parameters by splitting the url at the ?
function getParams() {
var uri = window.location.toString();
if (uri.indexOf("?") > 0) {
var params = uri.substring(uri.indexOf("?") + 1, uri.length);
return params;
}
return "";
}
// Split the string by & and then split each pair by = then return the object
function paramsToObject() {
var params = getParams().split("&");
var obj = {};
for (p in params) {
var arr = params[p].split("=");
obj[arr[0]] = arr[1];
}
return obj;
}
</script>
If using Angular:
You can use the qs npm module suggested in the answer by danday74.
const str = 'abc=foo&def=%5Bbar%5D&xyz=5'
// reduce takes an array and reduces it into a single value
const nameVal = str.split('&').reduce((prev, curr) => {
// see output here in console for clarity:
console.log('curr= ', curr, ' prev = ', prev)
prev[decodeURIComponent(curr.split('=')[0])] = decodeURIComponent(curr.split('=')[1]);
return prev;
}, {});
// invoke
console.log(nameVal);
So, I am testing the JS includes() method, so I created a search input field, where I can search through the notes I created with live rerendering. Now my question is:
When I pass no searchtext at all, all the notes are shown, but when I enter a character or a word, the notes get filtered right away.
Example code:
const filters = {
searchText: ''
}
// Render application notes
const renderNotes = (notes, filters) => {
const filteredNotes = notes.filter((note) => {
return note.title.toLowerCase().includes(filters.searchText.toLowerCase())
})
document.querySelector('#notes').innerHTML = ''
filteredNotes.forEach((note) => {
const noteEl = generateNoteDOM(note)
document.querySelector('#notes').appendChild(noteEl)
})
}
I understand from this, that true is always returned in such a case..
Would appreciate any clarification to this subject!
Thanks!
The .includes() function has to match the functionality of .indexOf() for consistency, and .indexOf() always matches the empty string in any target string. From MDN:
An empty string searchValue will match at any index between 0 and str.length.
It's a little counter-intuitive, but consider this:
var str = "something";
console.log(str.includes("")); // Imagine this returns false ...
str += "";
console.log(str.includes("")); // !!