My web application uses google firestore to upload documents. However, firestore hashes the documents name but I want to extract that name and use it. The formatted string looks like this.
const url = "https://storage.googleapis.com/test/agency-register-crrRhaUSWopn4QRc2M54MX.png";
const url = "https://storage.googleapis.com/test/agency-register-documents-crrRhaUSWopn4QRc2M54MX.png";
const url = "https://storage.googleapis.com/test/agencyRegister-crrRhaUSWopn4QRc2M54MX.png";
const url = "https://storage.googleapis.com/test/agency-crrRhaUSWopn4QRc2M54MX.png";
As you can see, after test/ the file name comes first and before the files type there is a hash and finally the file type which is .png here. How can I get the english words(agency-register, agency-register-documents, agencyRegister, et.) or the file name from these strings? I'm trying to create a dynamic structure.
I don't know the required logic, so I didn't do anything.
Sounds like a job for a regular expression.
For example:
let pattern = /https:\/\/storage\.googleapis\.com\/test\/([\w-]*)-\w*.png/;
let url = "https://storage.googleapis.com/test/agency-register-crrRhaUSWopn4QRc2M54MX.png";
let name = url.match(pattern)[1];
To see what it does, https://regex101.com/r/7TcJuI/1
If you don't want to solve it with regular expressions.
You can do it the way suggested in the comment.
const url = "https://storage.googleapis.com/test/agencyRegister-crrRhaUSWopn4QRc2M54MX.png";
const parts = url.split("test/")[1].split("-");
parts.pop();
const result = parts.join("-");
console.log(result);
Related
How can I search the values in an Object from strings, something like:
const query = "['arg1']['arg2']"
const renderImage = async (index) => {
const data = await fetchImage(index)
const image = document.querySelector('.div')
image.setAttribute("src", data`${query}`)
}
The fetch function is perfect working.
Edit:
The image source is in the data['arg1']['arg2']. If I use image.setAttribute("src", data['arg1']['arg2']) the code runs fine, but I need to do this dynamically and concatenate strings will help me.
Summing up: can I get the same result data['arg1']['arg2'] concatenating object and "query" (['arg1']['arg2'])?
you can store the path as an array of keys and access it like this
const query = ['arg1', 'arg2']
...
image.setAttribute("src", query.reduce((o, k)=>o[k], data))
It seems you are trying to extract the property names you want, from a poorly formatted string. Ideally, you would get query into a better format to begin with, so you don't have to parse the string. For instance, if you could get query as two separate variables:
const query1 = 'arg1';
const query2 = 'arg2';
image.setAttribute("src", data[query1][query2]);
you could also store query in a better data type to do this, like const query = { arg1: 'arg1', arg2: 'arg2' }; then access with dot syntax data[query.arg1][query.arg2].
But if you must keep query as this weirdly formatted string for some reason, you can do something like this, parsing the string into it's parts, putting them into an array, then using the array to access the right data within data.
let query = "['arg1']['arg2']";
query = query.slice( 2 ).slice( 0, -2 ).split( "']['" );
image.setAttribute( "src", data[query[0]][query[1]] );
How to pass a dynamic value in between get api url?
I have a ref that is connected to the input and want value of that input to be passed into a string.
This does not work:
const location = useRef("Warsaw");
"http://api.weatherstack.com/current?&query={location.current.value}"
You have incorrect dynamic string syntax. You should use template literals:
const location = useRef("Warsaw");
let url = `http://api.weatherstack.com/current?&query=${location.current.value}`
You can use template literals
const location = useRef("Warsaw");
const uri = `http://api.weatherstack.com/current?&query=${location.current.value}`
I want to capture screenshots on my remote virtual machine without using display. I came across a library in nodejs 'capture screenshot' (https://github.com/sindresorhus/capture-website) which is pretty straightforward.
Taking screenshot of a single link is fairly simple, however taking multiple screenshots becomes tricky. I don't want to put links manually as it will be time consuming. I am running a script to get all anchor tags in python and saving a csv file of links gathered. This is how it looks when I convert the saved csv file to a JavaScript array.
[ 'https://www.google.com/imghp?hl=en&tab=wi',
'https://maps.google.com/maps?hl=en&tab=wl',
'https://play.google.com/?hl=en&tab=w8',
'https://www.youtube.com/?gl=US&tab=w1',
'https://news.google.com/nwshp?hl=en&tab=wn',
'https://mail.google.com/mail/?tab=wm',
'https://drive.google.com/?tab=wo',
'https://www.google.com/intl/en/about/products?tab=wh',
'https://accounts.google.com/ServiceLogin?hl=en&passive=true&continue=https://www.google.com/',
'https://www.google.com/url?q=https://lifeinaday.youtube/%3Futm_source%3Dgoogle%26utm_medium%3Dhppcta%26utm_campaign%3D2020&source=hpp&id=19019062&ct=3&usg=AFQjCNEJMAD58Mjdnro8Mjm-RtJ3nfEIZA&sa=X&ved=0ahUKEwi98PWM4-HqAhVh1uAKHeYGCPwQ8IcBCAU'
]
I want to convert the above array to the array shown below.
[
['https://www.google.com/imghp?hl=en&tab=wi', 'anyanme'],
['https://maps.google.com/maps?hl=en&tab=wl','anyanme'],
['https://play.google.com/?hl=en&tab=w8','anyanme'],
['https://www.youtube.com/?gl=US&tab=w1','anyanme'],
['https://news.google.com/nwshp?hl=en&tab=wn','anyanme'],
['https://mail.google.com/mail/?tab=wm','anyanme'],
['https://drive.google.com/?tab=wo','anyanme'],
['https://www.google.com/intl/en/about/products?tab=wh','anyanme'],
['https://accounts.google.com/ServiceLogin?hl=en&passive=true&continue=https://www.google.com/','anyanme'],
['https://www.google.com/url?q=https://lifeinaday.youtube/%3Futm_source%3Dgoogle%26utm_medium%3Dhppcta%26utm_campaign%3D2020&source=hpp&id=19019062&ct=3&usg=AFQjCNEJMAD58Mjdnro8Mjm-RtJ3nfEIZA&sa=X&ved=0ahUKEwi98PWM4-HqAhVh1uAKHeYGCPwQ8IcBCAU','anyanme']
];
``
I am newbie to javscript and having a hard time to solve this. Any help will be appreciated.
It looks like the library you're using wants an array of pairs, with a URL and a file name.
I would map your original array to the array of pairs, but you'll have to figure out what you want to do for file names.
Assuming you have a function, named toFileName that will take a URL string and return a file name that you want for that URL, you could map the original array into the array of pairs like this:
const pairArr = originalArray.map((url) => {
const fileName = toFileName(url);
return [url, fileName];
});
If you just want to try to use the URL as the filename, you could just do this:
const pairArr = originalArray.map((url) => {
return [url, url];
});
This will be an issue with most URLs, though, as they'll have characters that are invalid for filenames. If you need a file extension with this approach, you could use string concatenation (url + '.png') for the second item in the returned pair.
You ca achieve it with a Map and regex
const arr = ['https://www.google.com/imghp?hl=en&tab=wi',
'https://maps.google.com/maps?hl=en&tab=wl',
'https://play.google.com/?hl=en&tab=w8',
'https://www.youtube.com/?gl=US&tab=w1',
'https://news.google.com/nwshp?hl=en&tab=wn',
'https://mail.google.com/mail/?tab=wm',
'https://drive.google.com/?tab=wo',
'https://www.google.com/intl/en/about/products?tab=wh',
'https://accounts.google.com/ServiceLogin?hl=en&passive=true&continue=https://www.google.com/',
'https://www.google.com/url?q=https://lifeinaday.youtube/%3Futm_source%3Dgoogle%26utm_medium%3Dhppcta%26utm_campaign%3D2020&source=hpp&id=19019062&ct=3&usg=AFQjCNEJMAD58Mjdnro8Mjm-RtJ3nfEIZA&sa=X&ved=0ahUKEwi98PWM4-HqAhVh1uAKHeYGCPwQ8IcBCAU',
'',
];
function extractName(str) {
const regex = /https:\/\/(.*?)\//g;
const ret = regex.exec(str);
return (ret && ret[1]) || null;
}
const items = arr.map(x => [
x,
extractName(x),
]);
console.log(items);
There is way to save only part of the string object into async-storage ?
for example if inside the "result.userPrincipalName" it save " bob23#hotmail.com "
so i want it will be save only the "bob23" , so what is the way to do it ?
await AsyncStorage.setItem(
'AZURE-USERNAME',
JSON.stringify(
result.userPrincipalName.substring(0, data.indexOf('#'))
)
);
You condo something like this.
You can remove part of the string after a certain character.
As I can see in the documentation. It stores as a key-value pair.
So I made changes
let data = JSON.stringify(result.userPrincipalName);
//here substring will remove characters after and including `#`
data = data.substring(0, data.indexOf('#'));
await AsyncStorage.setItem('AZURE-USERNAME', data);
I believe that you need to handle your desirable data on top level (add new input to user / new field in db with desired data etc. I don't know whereby you get your userPrincipalName).
But, if it's not possible, you can follow something like this:
const name = result.userPrincipalName.split('#')[0];
if (!name) throw new Error('Invalid email');
await AsyncStorage.setItem('AZURE-USERNAME', name);
Simply you can use split function in Javascript. More information
//Split the mame using split function
const splitName = result.userPrincipalName.split("#");
//Get the split value and save it
//After you splitting [0] mean first character set
const name = splitName[0];
//Save it to AsyncStorage
await AsyncStorage.setItem("AZURE-USERNAME", JSON.stringify(name));
I'm looking for a way to get the query string part of a url using node.js or one of it's extension module.
I've tried using url and express but they give me an array of parameters.
I want to original string.
Any ideas ?
example; for:
http://www.mydom.com?a=337&b=33
give me
a=337&b=33
(with or without the ?)
Use url.parse. By default it will return an object whose query property is the query string. (You can pass true as the second argument if you want query to be an object instead, but since you want a string the default is what you want.)
var url = require('url');
var urlToParse = 'http://www.mydom.com/?a=337&b=33';
var urlObj = url.parse(urlToParse);
console.log(urlObj.query);
// => a=337&b=33
How about using the built-in url.parse method?