Why url query component is not removed? - javascript

I wrap the href to URL, and try to remove one component, remove with delete, but component does not disappear. Do you know why?
let url = new URL(window.location.href);
let p = url.searchParams['postId'+$(".selected").length];
delete p;
window.location = url.toString();
I tried this:
const filteredItems = url.searchParams.filter(key => url.searchParams[key] == postID);
let key = filteredItems.keys.first;
url.searchParams.delete(key);
but it says
Uncaught TypeError: url.searchParams.filter is not a function
I tried now this expression, but filter does not work, do you have any idea why?
function togglePost(postID) {
let url = new URL(window.location.href);
const filteredItems = Object.keys(url.searchParams).filter(key =>
url.searchParams[key] == postID
);
let key = filteredItems.keys.first;

The delete operator deletes properties from objects.
You are trying to delete a variable. This fails silently.
To delete something from a URLSearchParams object, use the delete method:
let url = new URL('http://example.com/foo.cgi?a=1&b=2');
console.log(url.toString());
url.searchParams.delete('a');
console.log(url.toString());

Related

how can I use a variable value to define a new variable in JavaScript? [duplicate]

This question already has an answer here:
using variable results (contents) to create new variables
(1 answer)
Closed 10 months ago.
I have a list
const StudentCode = {
Jack: 32658495,
Rose: 35621548,
Lita: 63259547,
Seth: 27956431,
Cathy: 75821456,
};
how can I use these peoples numbers if their names matches another variable result?
We have
var name = *selected server-side student names*
and by these * signs I mean it's a great list that name gives up but it only gives up one name out of that list at the time we call it.
If one of these students is selected by name variable, how can I use the number defined in front of that name in const StudentCode to generate a url?
Suppose you get Rose! Then the number for Rose is: 35621548 and the url for example will be https://www.35621548.com. What code can we use to generate this url for example in console?
console.log(url)
Use this:
if (StudentCode.hasOwnProperty(name){
const url = `https://www.${StudentCode[name]}.com`
}
This function will return you the url on the basis of the student name that is passed in this function.
function returnURL(studentName){
const StudentCode = {
Jack: 32658495,
Rose: 35621548,
Lita: 63259547,
Seth: 27956431,
Cathy: 75821456,
};
if (!!!StudentCode[studentName]) return "";
return "https://" + StudentCode[studentName] + ".com";
}
console.log(returnURL("Rose"));
Hope, this helps!!
const StudentCode = {
Jack: 32658495,
Rose: 35621548,
Lita: 63259547,
Seth: 27956431,
Cathy: 75821456,
};
let studentName = "Jack"
const url = `https://${StudentCode[studentName]}.com`
console.log(url)
export const studentUrlModule = (function() {
const studentCode = {
Jack: 32658495,
Rose: 35621548,
Lita: 63259547,
Seth: 27956431,
Cathy: 75821456,
};
const url = 'https://$code.com'
const generateUrl = function(code = '') {
if (!url) {
throw new Error('Url is not defined')
} else if (!code) {
throw new Error('Code is not defined')
};
return url.replace('$code', `${code}`);
}
function getCode(name = '') {
const code = studentCode[name];
if (!code) {
throw new Error(`There is no code with name(${name}).`);
}
return code;
}
function getUrl(name = '') {
if (!name) {
throw new Error('StudentName is undefined')
};
const code = getCode(name);
const studentUrl = generateUrl(code);
return studentUrl;
}
return {
generateUrl,
getCode,
getUrl,
};
}());
Maybe it helps. If the code was not founded then it throws an error. Please use try, catch error handlers to handle errors.
-- Update
I updated the code and as you can see it's a module and you need to import it everywhere you like to use this.
if you are not familiar with modules and how to use them inside the browser check documents.
Mozila documents
Super Simple Start to ESModules in the Browser

Logging array returns number when it's not suppose to

Basically I wanted the data from JSON to be accessible outside of the xml function as I have multiple functions I want to use it for.
So when I first tried it out and tried logging it, it did show the arrays with the objects in it. But when I did the same but checked the length instead it came out as zero. I looked this up and found out that it happens because both functions are running synchronously. So I looked into promises and implemented it like this:
let allTasks = []
// Read data
const dataPromise = new Promise((resolve, reject)=>{
const xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status ==200) {
const myData = JSON.parse(this.responseText)
allTasks = allTasks.push.apply(allTasks, myData)
resolve()
}
}
xhttp.open("GET", "data.json", true);
xhttp.send();
})
dataPromise.then(()=>{
dataUse()
})
// Show data
dataUse = () =>{
console.log(allTasks)
// All variables
const todos = document.querySelector('.todo')
const todoInput = document.getElementById('new-todo')
const added = document.getElementById('added')
const itemsLeft = document.querySelector('.items-left > span')
allTasks.forEach((datas)=>{
const todo = document.createElement('div')
todos.appendChild(todo)
const input = document.createElement('input')
input.setAttribute('type', 'checkbox')
input.setAttribute('id', datas.name)
input.setAttribute('class', 'checks')
todo.appendChild(input)
const label = document.createElement('label')
label.setAttribute('for', datas.name)
label.setAttribute('class', `${datas.name} tasks`)
todo.appendChild(label)
const span = document.createElement('span')
label.appendChild(span)
const paragraph = document.createElement('p')
paragraph.innerHTML = datas.todo
label.appendChild(paragraph)
})
}
But now logging it gives me a number rather than the array with the objects, hence the function won't be able to do what it is suppose to.
So how do I fix this?
The problem is that you don't have to assign the return value of a push operation to the variable because the return value is the length of the array.
Just push into the array and the variable will have the latest content.
Instead of allTasks = allTasks.push.apply(allTasks, myData),
do allTasks.push(allTasks, myData).
It'll be good if you use const in place of let.
const allTasks = [];
allTasks.push(allTasks, myData);

Javascript Object Issue not able to send particular key

Hi i have a weird javascript issue.Here's my code I am not able to send these keys in my designOrder object. My Object does not have these fronImage and backImage keys that i am sending in my code.
let designOrder = await dbCall();
let allImages = []
allImageIds.push(designOrders.frontImageId);
allImageIds.push(designOrders.backImageId);
allImages = await dbCall();
let allImagesHash = {};
allImages.forEach(obj) => {
obj.image = JSON.parse(image)
allImagesHash[image.id] = image;
}
if(designOrder.backImageId){
designOrder.backImage = allImagesHash[designOrder.backImageId]
}
// if i do console.log("1", designOrder.backImage) it will log the designOrder.backImage
if(designOrder.frontImageId){
designOrder.frontImage = allImagesHash[designOrder.frontImageId]
}
// if i do console.log("2", designOrder.frontImage) it will log the designOrder.backImage
// but while console.log("3", designOrder) it will not show the backImage and frontImage keys
return designOrder;
It actually solved it after the first dbCall() i have added this line of code and it worked.
designOrder = designOrder.toJSON();
toJson function is defined within the mongoose schema.

Let statement in Explorer?

My project (with HTML and JavaScript) doesn't work in Internet Explorer and I think that is because I use a let statement in a JS method. Can I add some external libraries that makes it possible to read the let statements? Or can I rewrite the function? I don't really know how the let method works so can anyone tell me how to rewrite these lines:
initializeData = function()
{
//Check URL and QueryString
var url = window.location.href.toString();
var queryString = (url.split("?"))[1];
if (queryString == undefined || queryString=="" || queryString==null)
resetData();
else //filter data based on URL QueryString
{
const query = decodeURI(queryString);
const result = query.split('&');
result.forEach(function(item){
const [cat, values] = item.split('='); //ERROR
const isArray = cat.endsWith('[]');
let pair;
if (isArray)
{
const p = values;
pair = { cat, 'values': [values] };
}
else
{
pair = {cat, values };
}
currentFilters.push(pair);
});
RunFilter();
}
}
I need pair to be on the same structure since I am using it in the RunFilter() method.

How to get URL parameters in JavaScript?

I'm using Vue, but I'm not using vue-router.
How can I get URI parameters?
I found one way to get URI by using root el property.
But is there any proper way to get the parameters as I want to send them to
backend and get a response from server and display it.
You can get the URL parameters by using window.location.search:
const queryString = window.location.search;
console.log(queryString);
// ?product=troussers&color=black&newuser&size=s
For parsing parameters of the query string, use URLSearchParams:
const urlParams = new URLSearchParams(queryString);
For more info, read this tutorial.
Since you are not using vue-router, I don't think you'll be able to access your params. So your only chance is to use the URL api as:
const URL = new URL(window.location.href);
const getParam = URL.searchParams.get('foo');
This will give you the value of foo in ?foo=bar
Alternatively, you can do something like this.
new Vue({
el: '#app',
data () {
return {
params: window.location.href.substr(window.location.href.indexOf('?'))
}
},
methods: {
getParam (p) {
let param = new URLSearchParams(this.params);
if(param.has(p)){
return param.get(p)
}else{
false
}
}
},
})
Now, just get the param using getParam('foo')
We don't use vue router for the moment either. We use the following script to parse args.
var args = {};
var argString = window.location.hash;
//everything after src belongs as part of the url, not to be parsed
var argsAndSrc = argString.split(/src=/);
args["src"] = argsAndSrc[1];
//everything before src is args for this page.
var argArray = argsAndSrc[0].split("?");
for (var i = 0; i < argArray.length; i++) {
var nameVal = argArray[i].split("=");
//strip the hash
if (i == 0) {
var name = nameVal[0];
nameVal[0] = name.slice(1);
}
args[nameVal[0]] = decodeURI(nameVal[1]);
}
Route properties are present in this.$route.
this.$router is the instance of router object which gives the configuration of the router.
You can get the current route query using this.$route.query

Categories