split variables from array - javascript

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.

Related

How to separate a string as according to a condition, using split?

good morning I have these text strings:
json_schema.account_overview.name
json_schema.no_owned.contact.contact
but now I'm trying to separate according to the string 'json_schema.no_owned', doing like this:
my_string.split ("json_schema.no_owned."). filter (x => x);
but doing a console.log of that result I get this
the first arrangement is fine, since to that same arrangement I can apply another split and I will have again separated by '.'
but the second fix has nothing to do with what I was saying should be after 'json_schema.no_owned.' (note the period at the end)
This way I am trying to do it:
let string ="json_schema.no_owned.contact.contact";
let arrayString = [
'json_schema.no_owned.contact.contact',
'json_schema.account_overview.name'
];
let schema = "";
for(let i in arrayString){
schema = arrayString[i].split("json_schema.no_owned.").filter(x => x);
console.log(schema);
}
I only want to have in an array the elements that are after 'json_schema.no_owned'
Thanks.
You can check if element has "json_schema.no_owned." part at all:
let string ="json_schema.no_owned.contact.contact";
let arrayString = [
'json_schema.no_owned.contact.contact',
'json_schema.account_overview.name'
];
let schema = "";
for(let i in arrayString){
if (arrayString[i].includes("json_schema.no_owned.")) {
schema = arrayString[i].split("json_schema.no_owned.").filter(x => x);
console.log(schema);
}
}
Maybe you can use a short way to do it.
let arrayString = [
'json_schema.no_owned.contact.contact',
'json_schema.account_overview.name'
];
const schemas = arrayString.filter(x => x.includes("json_schema.no_owned."))
.map(x => x.split("json_schema.no_owned.")[1]);

How to extract multiple URL from string

I have string like this - "https://gaana.com/song/dil-chahte-hohttps://www.youtube.com/watch?v=MWnFCGXjjS0&list=PLs1-UdHIwbo5p-8wh740E7CRhIoKq5APmhttps://www.youtube.com/watch?v=MWnFCGXjjS0&list=PLs1-UdHIwbo5p-8wh740E7CRhIoKq5APm"
In here I have three urls, how can i separate them and push them into an array. the url's can be start with http or https or directly from www or any valid url. I want the output like -
[
"https://gaana.com/song/dil-chahte-ho",
"https://www.youtube.com/watch?v=MWnFCGXjjS0&list=PLs1-UdHIwbo5p-8wh740E7CRhIoKq5APm",
"https://www.youtube.com/watch?v=MWnFCGXjjS0&list=PLs1-UdHIwbo5p-8wh740E7CRhIoKq5APm"
]
Try this:
var t = "https://gaana.com/song/dil-chahte-hohttps://www.youtube.com/watch?v=MWnFCGXjjS0&list=PLs1-UdHIwbo5p-8wh740E7CRhIoKq5APmhttps://www.youtube.com/watch?v=MWnFCGXjjS0&list=PLs1-UdHIwbo5p-8wh740E7CRhIoKq5APm"
t = t.split("http").map(x => { return "http"+x }).slice(1)
First split the string on "http", which gives you an array. Then append the http to each element of the string. Unfortunately you end up with the first element in the array being "http" that's why you need to slice to remove it.
You can do that with the following code in Python:
links_str = "https://gaana.com/song/dil-chahte-hohttps://www.youtube.com/watch?v=MWnFCGXjjS0&list=PLs1-UdHIwbo5p-8wh740E7CRhIoKq5APmhttps://www.youtube.com/watch?v=MWnFCGXjjS0&list=PLs1-UdHIwbo5p-8wh740E7CRhIoKq5APm"
links = ["http"+str(link) for link in links_str.split("http")][1:]
Maybe you can try to do something like this in JavaSript.
var urls = "https://gaana.com/song/dil-chahte-hohttps://www.youtube.com/watch?v=MWnFCGXjjS0&list=PLs1-UdHIwbo5p-8wh740E7CRhIoKq5APmhttps://www.youtube.com/watch?v=MWnFCGXjjS0&list=PLs1-UdHIwbo5p-8wh740E7CRhIoKq5APm"
urls = urls.split("https://").map(val => { return "https://"+val }).slice(1)
console.log(urls);
try this one it will help to split https value in the string
const string = "https://gaana.com/song/dil-chahte-hohttps://www.youtube.com/watch?v=MWnFCGXjjS0&list=PLs1-UdHIwbo5p-8wh740E7CRhIoKq5APmhttps://www.youtube.com/watch?v=MWnFCGXjjS0&list=PLs1-UdHIwbo5p-8wh740E7CRhIoKq5APm"
const http = string.split("http://").map(val => { return "http://"+val }).slice(1)
const https = string.split("https://").map(val => { return "https://"+val }).slice(1)
const array = [...http, ...https]
console.log(array)
One more way add to space or other delimiter before http and split string:
const str = "https://gaana.com/song/dil-chahte-hohttps://www.youtube.com/watch?v=MWnFCGXjjS0&list=PLs1-UdHIwbo5p-8wh740E7CRhIoKq5APmhttps://www.youtube.com/watch?v=MWnFCGXjjS0&list=PLs1-UdHIwbo5p-8wh740E7CRhIoKq5APm";
const result = str.replace(/http/g, ' $&').split(' ');
// result ["", "https://gaana.com/song/dil-chahte-ho", "https://www.youtube.com/watch?v=MWnFCGXjjS0&list=PLs1-UdHIwbo5p-8wh740E7CRhIoKq5APm", "https://www.youtube.com/watch?v=MWnFCGXjjS0&list=PLs1-UdHIwbo5p-8wh740E7CRhIoKq5APm"]
For some reason I had to convert a String with multiple URLS to an Array. So I used a regex to handle the urls and .match() method for creating an Array.
let urls = '[https://website.com/slug, https://website.com/other-slug]';
function convertUrlStringToArray(urls) {
let expression = /\b(https?:\/\/\S*\b)/g;
let regex = new RegExp(expression);
return urls.match(regex);
}
Output an Array:
[ 'https://website.com/slug', 'https://website.com/other-slug' ]

Get all unique values in array after validating content

If I have this very simple array:
let result = ["doc1.rtf","doc2.rtf","test/doc4.rtf","test/doc4.rtf","test/doc6.rtf"]
I could find the unique occurrences by running something like.
let unique = [...new Set(result)];
Which will return me:
["doc1.rtf","doc2.rtf","test/doc4.rtf","test/doc6.rtf"]
But what I want to do is search the array for anything unique after filtering out the contents of anything up to a leading slash. So the array will look like this below before I filter out the duplicate test/
let filtered = ["doc1.rtf","doc2.rtf","test/","test/","test/"]
Thanks in advance. Is there a way to do above in one operation?
I hope I understand the question correctly, but you can play around with map. For example:
result.map(r => r.split('/')[0])
# ["doc1.rtf", "doc2.rtf", "test", "test", "test"]
result.map(r => r.replace(/\/.*/, '/'))
# ["doc1.rtf", "doc2.rtf", "test/", "test/", "test/"]
might yield what you're looking for.
To remove anything up to a leading slash you could use map with split:
let result = ["doc1.rtf","doc2.rtf","test/doc4.rtf","test/doc4.rtf","test/doc6.rtf"];
result.map(i => i.split('/')[0]);
// ["doc1.rtf", "doc2.rtf", "test", "test", "test"]
And than look for unique elements
let unique = [...new Set(result)];
//["doc1.rtf", "doc2.rtf", "test"]
You could accomplish the filtration in one pass by mapping each item of the array to a resolver, then using a Set for membership.
const uniqMap = resolver => function uniqMapping(array) {
const existing = new Set(),
result = []
for (let i = 0; i < array.length; i++) {
const item = array[i]
const resolvedItem = resolver(item)
if (existing.has(resolvedItem)) {
continue
}
existing.add(resolvedItem)
result.push(resolvedItem)
}
return result
}
let data = ["doc1.rtf","doc2.rtf","test/doc4.rtf","test/doc4.rtf","test/doc6.rtf"]
console.log(
uniqMap(item => item.split('/')[0])(data),
) // [ 'doc1.rtf', 'doc2.rtf', 'test' ]

Remove Strings From Array

I'm trying to make an array of objects from the browsing history that can become links in a React list.
What this does is takes the history element and pushes it to the user object, then I take the name and ID, and splice it back into the array. I then filter it down to distinct values.
What I am left with, is an array that looks like this:
[{id1,name1},{id2,name2},{id3,name3},"id1","id2","id3"]
which is almost exactly what I want, except if I'm going to map that to create links, I need to get rid of the string values.
It occurred to me to try skipping the history element and just make an array of matches, and any number of other things.
pop and shift don't work to isolate the first object because then the whole function continually returns a single item.
This is the only way I have gotten a result close to what I want, I just need a simple way of filtering out string values from an array after it's created, or maybe before it's mapped out.
const getLead = async _id => {
const res = await axios.get(`/api/leads/${_id}`);
dispatch({
type: GET_LEAD,
payload: res.data
});
const { name } = res.data
const match = { name, _id }
const setPrevious = () => {
const prevLeads = user.prevLeads
const history = createBrowserHistory(getLead);
const prevLead = history.location.pathname.slice(6);
prevLeads.push(prevLead);
return prevLeads;
}
const prevLeads = setPrevious();
const [...spliceLeads] = prevLeads.splice(0,1,match,match);
const distinct = (value, index, self) => {
return self.indexOf(value) === index;
}
const recentLeads = prevLeads.filter(distinct) ;
console.log(spliceLeads)
}
You just check the type in your .filter logic:
const array = [
{ test: 'ing' },
1,
new Date(),
'this should be removed'
];
const result = array.filter(e => typeof e !== 'string');
console.log(result);
The solution what has been provided already works like charm, that should be used for your solution, below I'm providing a bit different way to figure out if the element is a string or not.
I guess filter() is a good way to test each elements on an array and return only the passing once as a result. If you call on each item Object.prototype.toString.call(e) then it will return as a text if you have [object String] or something else. This can be also used to filter out your string values from your array.
See the example below:
const prevLeads = [{id:'id1',name: 'name1'},{id: 'id2',name:'name2'},{id:'id3',name:'name3'},"id1","id2","id3"];
const filter = e => Object.prototype.toString.call(e) !== '[object String]';
const recentLeads = prevLeads.filter(filter);
console.log(recentLeads);
I hope that helps!

Get number from the string JS / Lodash / TypeScript

I have a link that comes in as a string, for example:
let data = [
'/api/customer’,
'/api/customer/123’,
'/api/customer/123/details’
];
I need to extract the numeric ID if there is one. The only way I found is trough _.isNaN():
const myStrArray = type.split('/');
const numericsArray = _.filter(myStrArray, urlPart => !_.isNaN(parseInt(urlPart, 10)));
const id = numericsArray[0]; // undefined/123
Is there a better way to do this?
You can iterate the array with Array.flatMap() (or lodash _.flatMap()), and use String.match() with a RegExp to get a sequence of numbers.
Note: this RegExp assumes that these are the only numbers in the string. You might want to fine tune it, if there's a possibility for other numbers.
let data = [
'/api/customer',
'/api/customer/123',
'/api/customer/123/details'
];
const result = data.flatMap(str => str.match(/\d+/));
console.log(result);
User regex and Array#map and Array#flat like so. You need to use ||[] in case a number was not found.
const data = [
'/api/custome',
'/api/customer/123',
'/api/customer/123/details'
];
const res = data.map(a=>a.match(/\d+/)||[]).flat();
console.log(res);

Categories

Resources