How can I edit this code to handle multiple delimiters? Currently, it checks for either %7 or |relevance and removes it. But it does not handle multiple delimiters such as in the 2 URL examples below.
https://www.example.com/en-us/search?pq=marketing+agriculture%7Crelevance%7CbestSeller%3Atrue
https://www.example.com/en-us/search?pq=marketing+agriculture|Crelevance|CbestSeller%3Atrue
It should only grab the words: marketing agriculture from the two URLs above.
const params = new URLSearchParams(window.location.search);
if (params.has('pq')) {
const pq = params.get('pq').split('&7').pop().replace('|relevance', '');
console.log(pq);
}
Desired output: To get only the search terms from the URL.
Use Regex:
const params = new URLSearchParams(window.location.search);
const regX = /(\w+[\+]?\w+)/gm;
if (params.has('pq')) {
const pq = params.get('pq').match(regX);
console.log(pq && pq[0]);
}
Here is a way to do it:
let a = "https://www.example.com/en-us/search?pq=marketing+agriculture%7Crelevance%7CbestSeller%3Atrue"
// Converts Params to Object
const parseParams = (querystring) => {
// parse query string
const params = new URLSearchParams(querystring);
const obj = {};
// iterate over all keys
for (const key of params.keys()) {
if (params.getAll(key).length > 1) {
obj[key] = params.getAll(key);
} else {
obj[key] = params.get(key);
}
}
return obj;
};
let aURL = new URL(a) // get the URL instance
let queryObj = parseParams(aURL.search) // grab and parse the parameter string (.search)
let search = queryObj.pq.split('|')[0] // grab the 'pq' prop (i.e that holds the search value.) and split it to get the actual search string
console.log(search)
Related
I have set of array of objects containing url, name and address where I want to get the id from url and join them by a comma.
let arrayOfObjects = [
{ url: 'http://localhost:3000/redApi?id=001&name=abc&address=1234#gmail.com' }
{ url: 'http://localhost:3000/redApi?id=002&name=xyz&address=5647#gmail.com' }
{ url: 'http://localhost:3000/redApi?id=undefined&name=pqr&address=980#gmail.com' }
]
Also if there is "undefined" I want to pass it an empty.
Expected output:
001,002,
Here is my code
let arrayOfObjects = [
{ url: 'http://localhost:3000/redApi?id=001&name=abc&address=1234#gmail.com' }
{ url: 'http://localhost:3000/redApi?id=002&name=xyz&address=5647#gmail.com' }
{ url: 'http://localhost:3000/redApi?id=undefined&name=pqr&address=980#gmail.com' }
]
let urlId = arrayOfObjects.map(x=> x.url)
let getUrl = new URLSearchParams("?" + urlId?.url?.split("?")[1])
let dataId = getUrl.get('id')
console.log(dataId)
First you can map every element of the array to the parameter. You can use URL() to easily get the searchParams from a URL.
let urlIds = arrayOfObjects.map(x => new URL(x.url).searchParams.get('id'));
Now urlIds is an array of the id query string parameters of every URL in the arrayOfObjects array.
Query string parameter values are always strings. There is no such thing as undefined there. If you want to treat "undefined" as empty, you could modify the .map() above, or just use a separate .map() do so. I find the latter to be cleaner.
urlIds = urlIds.map(value => value === "undefined" ? "" : value);
Then finally, if you want them to be joined together separated by a comma, use the .join() method. So the whole code would be:
let arrayOfObjects = [
{ url: 'http://localhost:3000/redApi?id=001&name=abc&address=1234#gmail.com' },
{ url: 'http://localhost:3000/redApi?id=002&name=xyz&address=5647#gmail.com' },
{ url: 'http://localhost:3000/redApi?id=undefined&name=pqr&address=980#gmail.com' }
];
let urlIds = arrayOfObjects.map(x => new URL(x.url).searchParams.get('id'));
urlIds = urlIds.map(value => value === "undefined" ? "" : value);
let joinedUrlIds = urlIds.join(',');
console.log(joinedUrlIds);
You are using URLSearchParams not right take a look at the documentation:
https://medium.com/swlh/urlsearchparams-in-javascript-df524f705317
YOu first need to convert the url to actual URL objects:
let urlId = arrayOfObjects.map(x=> new URL(x.url))
Then you can get the params like so:
urlId.forEach(u => console.log(new URLSearchParams(u).get('id')))
I also noticed you are using a Array as a string when trying to get the id.
Try this:
let arrayOfId = arrayOfObjects.map((obj) => {
let url = obj.url;
let id = url.split("=")[1];
if(id.includes("&")){
id = id.split("&")[0];
}
if (id == "undefined") {
id = "";
}
return id;
});
console.log(arrayOfId);
Here check this out, it works fine.
let arrayOfObjects = [
{url:'http://localhost:3000/redApi?id=001&name=abc&address=1234#gmail.com'},
{url:'http://localhost:3000/redApi?id=002&name=xyz&address=5647#gmail.com'},
{url:'http://localhost:3000/redApi?id=undefined&name=pqr&address=980#gmail.com'}
];
let urlId = arrayOfObjects.map((x)=>{ if ( !isNaN(Number(x.url.slice(x.url.indexOf("?")+4,
x.url.indexOf("?")+5))) )
{ return x.url.slice(x.url.indexOf("?")+4, x.url.indexOf("&")) }
else {return ""}
});
console.log(urlId)
But if you exactly wanted to use URLSearchParams, I can also do it with that
If you prefer a one-liner:
let theIDs = arrayOfObjects
.map(x => new URLSearchParams(x.url.split('?')[1])
.get('id'))
.filter(x => x!=='undefined')
.join(',');
I have an array of urls that get pulled in with "videoJsonUrl" and i'm trying to get a variable from the urls that come in _id=XXXXXXXX
this is what I have so far, which works if I add the url in it manually:
const VideoUrl = "https://player.vimeo.com/external/444937644.sd.mp4?s=a6aa1fdd06df967a0cfc300dbfef1a24927e4f61&profile_id=165&oauth2_token_id=57447761"
const strs = VideoUrl.split('_id=');
const videoId = strs.at(-1)
console.log("Get Content Video ID",videoId);
I cant for the life of me get it to work "videoJsonUrl" though, I think the problem is that "videoJsonUrl" actually contains 3 urls, like this:
can anyone give me any pointers on how to do it?
You can construct a new URL object from each address, then use its searchParams property to get the parameter value of interest:
const urls = [
'https://player.vimeo.com/external/444937644.sd.mp4?s=a6aa1fdd06df967a0cfc300dbfef1a24927e4f61&profile_id=165&oauth2_token_id=57447761',
'https://player.vimeo.com/external/444937644.sd.mp4?s=a6aa1fdd06df967a0cfc300dbfef1a24927e4f61&profile_id=165&oauth2_token_id=57447823',
'https://player.vimeo.com/external/444937644.sd.mp4?s=a6aa1fdd06df967a0cfc300dbfef1a24927e4f61&profile_id=165&oauth2_token_id=57447915',
];
const results = urls.map(url => {
const id = new URL(url).searchParams.get('oauth2_token_id');
return id;
});
console.log(results); // [ "57447761", "57447823", "57447915" ]
URLSearchParams instances have a built-in entries iterator so this should also be fine:
const urls = [
'https://player.vimeo.com/external/444937644.sd.mp4?s=a6aa1fdd06df967a0cfc300dbfef1a24927e4f61&profile_id=165&oauth2_token_id=57447761',
'https://player.vimeo.com/external/444937644.sd.mp4?s=a6aa1fdd06df967a0cfc300dbfef1a24927e4f61&profile_id=165&oauth2_token_id=57447823',
'https://player.vimeo.com/external/444937644.sd.mp4?s=a6aa1fdd06df967a0cfc300dbfef1a24927e4f61&profile_id=165&oauth2_token_id=57447915',
];
const results = urls.map(url => {
const { oauth2_token_id } = Object.fromEntries(new URL(url).searchParams)
return oauth2_token_id;
});
console.log(results) // [ '57447761', '57447823', '57447915' ]
Since ids are all numeric, use a regular expression with a capturing group.
const rx = /_id=(\d+)/g
const m = rx.exec(url)
const ids=[]
while (m) {
ids.push(m[1])
m = rx.exec(url)
}
Use a Set if you need unique values. Use a Map and another capturing group if you need to capture the prefixed id name.
Or just parse the query string and get the values directly from the query map.
I'm trying to get from an array of multiple emails string this effect
if there is more than one email that ends with the same domain name of the email do not show me that filter for example:
const db = ['example#example.com', 'example2#example.com'];
const check = ['example3#example.com', 'another#anotherdomain.com'];
function findNotSimilar(check, db) {
const arr = check.filter((item) => db.indexOf(item) === -1);
return arr;
}
this returns ['example3#example.com', 'another#anotherdomain.com'], but I would like to return just ['another#anotherdomain.com'] array because the email ending with the same domain name
Here is the solution. But regarding the domains.. you have to consider domains with 2 parts like '.co.uk' in comparison with simple '.com'.
function Test() {
const db = ['example#example.com', 'example2#example.com'];
const check = ['example3#example.eu', 'another#anotherdomain.com'];
const dbFiltered = db.map(x => x.split('#')[1].split('.').slice(0, -1).join('.')).filter((x, y, z) => z.indexOf(x) === y);
const arr = check.filter((item) => dbFiltered.map(x => item.indexOf(x) === -1).every(x => x === true));
return arr;
}
Working Demo :
const db = ['example#example.com', 'example2#example.com'];
const check = ['example3#example.com', 'another#anotherdomain.com'];
// Split the array elements with domain name and creating a new array.
const formatDb = db.map((item) => item.split('#')[1]);
// Filtered out the element with different domain name.
const arr = check.filter((item) => formatDb.indexOf(item.split('#')[1]) === -1);
console.log(arr);
I have a string that needs to be converted to an object. But the string has the duplicated items. Since JSON Objects cannot contain 2 items with the same key. The second item is overwriting the first item.
How to merge the duplicate items and push to an array?
var string = "test-1=owner&test-1=driver&test-2=Yes&test-3=2&test-4=sun&test-4=moon&test-5=not-agree&test-6=dogs&test-6=testing+js+object&test-7=Testing+js+function&test-7=Testing+js+array"
var stringMod = string.split("&");
var stringObj = {};
stringMod.forEach(function(json) {
var jsonSplit = json.split("=");
stringObj[jsonSplit[0]] = [jsonSplit[1]];
});
console.log(stringObj,'stringObj');
Desired output:
{
"test-1": ["owner","driver"],
"test-2": ["Yes"],
"test-3": ["2"],
"test-4": ["sun","moon"],
"test-5": ["not-agree"],
"test-6": ["dogs","testing+js+object"],
"test-7": ["Testing+js+function","Testing+js+array"]
}
Here is the link to working fiddle: https://jsfiddle.net/sjoh9rqp/
Can you help me how to accomplish this ?
You can use a URLSearchParams to accomplish this, since it treats the string as url parameters it does do decoding though.
var string = "test-1=owner&test-1=driver&test-2=Yes&test-3=2&test-4=sun&test-4=moon&test-5=not-agree&test-6=dogs&test-6=testing+js+object&test-7=Testing+js+function&test-7=Testing+js+array"
var data = new URLSearchParams(string);
var obj = {};
for (let x of data.keys()){
obj[x] = data.getAll(x);
}
console.log(obj);
Using URLSearchParams to parse the query string helps simplify this
var string = "test-1=owner&test-1=driver&test-2=Yes&test-3=2&test-4=sun&test-4=moon&test-5=not-agree&test-6=dogs&test-6=testing+js+object&test-7=Testing+js+function&test-7=Testing+js+array"
const params = new URLSearchParams(string),
res = {};
params.forEach((v,k)=> {
res[k] = res[k] || []
res[k].push(v);
})
console.log(res)
For variety, here's the answer solved with reduce(), though I have to admit URLSearchParams is more elegant
var string = "test-1=owner&test-1=driver&test-2=Yes&test-3=2&test-4=sun&test-4=moon&test-5=not-agree&test-6=dogs&test-6=testing+js+object&test-7=Testing+js+function&test-7=Testing+js+array"
let obj = string.split('&').reduce((b,a) => {
let t = a.split('=');
if (b.hasOwnProperty(t[0])) b[t[0]].push(t[1]);
else b[t[0]] =[t[1]];
return b;
},{});
console.log(obj)
I'm creating a small application for connection to an API and append cards from magic the gathering JSON file onto an HTML webpage.
Those cards should be searchable and for that to happen I need to somehow create a filter()
I'm new and still in school at this subject.
I have pulled out only the card Names in the variable called "arr" and is trying to filter out / or match with a value from the search input field which is "strInput"
document.getElementById("searchButton").addEventListener("click", function(e){
const parentDiv = document.getElementById("cards");
if ( parentDiv.hasChildNodes() === true ) {
removeStuff();
} else {
filteredCards("https://api.magicthegathering.io/v1/cards");
}
}, false)
displayCards("https://api.magicthegathering.io/v1/cards");
function filteredCards(url) {
fetch(url)
.then((resp) => resp.json())
.then((data) => {
let myInput = document.getElementById("search").value;
let strInput = '"' + myInput + '"';
let arr = [];
for ( i in data.cards) {
let jsonValue = data.cards[i];
let name = jsonValue.name;
arr.push(name);
}
let result = strInput.match(arr);
console.log(result);
console.log(arr);
console.log(strInput);
});
};
console.log(arr); // returns NULL even thought the string matches.
There's two ways to do it simply that I could think of, .find() and .filter()
.find() is going to return you the first match, and as a string
.filter() is going to return you the all matches, and as an array
They both work with the same style of code, you're just changing the method name
arr.filter(item => item === strInput) | arr.find(item => item === strInput
Just as a little aside, there's a few things you could swap out to get those sweet sweet brownie points
let arr = [];
for ( i in data.cards) {
let jsonValue = data.cards[i];
let name = jsonValue.name;
arr.push(name);
}
Can instead be wrote using the map function
let arr = data.cards.map((card) => card.name);
.
Also, you don't need to do '"' + myInput + '"'; to make sure something is a string, which is what you might be trying to do there - you can just use myInput.toString() - of course your data might have the names include the quotes, but just in case this is a mistake I thought I'd point it out
The parameter passed to match method is not really a matcher but a string. The method expects a regex to be passed in.
Just build out a simple regex expression and then iterate over the data.cards and add it into the array if the condition passes. You can look at the filter available on the array object.
let myInput = document.getElementById("search").value;
let myInputRegex = new Regex(myInput, 'gi');
let arr = [];
const matchedTokens = data.cards.filter(card => {
return card.name.match(myInputRegex);
});
console.log(matchedTokens);
console.log(strInput);
You can make a method that uses array.Find() and pass in the arr and strInput. array.Find() will find the first match
getName: function (arr, strInput) {
var name = arr.find(n => n === strInput)
return name
}
Here's some more reading from the official mozzila docs
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
Thanks!
This was exactly what i was looking for :D
let myInput = document.getElementById("search").value;
let myInputRegex = new Regex(myInput, 'gi');
let arr = [];
const matchedTokens = data.cards.filter(card => {
return card.name.match(myInputRegex);
});
console.log(matchedTokens);
console.log(strInput);