How to get specific part of url string? - javascript

This is the result of the console.log below:
console.log('subscribe:', event.url);
"https://hooks.stripe.com/adapter/ideal/redirect/complete/src_1E2lmZHazFCzVZTmhYOsoZbg/src_client_secret_EVnN8bitF0wDIe6XGcZTThYZ?success=true"
Where I want to strip src_1E2lmZHazFCzVZTmhYOsoZbg and src_client_secret_EVnN8bitF0wDIe6XGcZTThYZ
How to achieve this?

Convert the string to a url, read the pathname and than split on / and take the last two parts.
var str = "https://hooks.stripe.com/adapter/ideal/redirect/complete/src_1E2lmZHazFCzVZTmhYOsoZbg/src_client_secret_EVnN8bitF0wDIe6XGcZTThYZ?success=true"
const parts = new URL(str).pathname.split('/').slice(-2)
console.log(parts)

If the query parameter ?success=true is optional (as in most cases is) you could
function getSrcAndSecret (url) {
const pts = /\/(src_[^/?]+)\/(src_client_secret_[^/?]+)/.exec(url);
return {
src: pts && pts[1] || "",
secret: pts && pts[2] || ""
}
}
// Demo:
const test1 = getSrcAndSecret("https://hooks.stripe.com/adapter/ideal/redirect/complete/src_1E2lmZHazFCzVZTmhYOsoZbg/src_client_secret_EVnN8bitF0wDIe6XGcZTThYZ?success=true");
const test2 = getSrcAndSecret("https://hooks.stripe.com/adapter/ideal/redirect/complete/src_1E2lmZHazFCzVZTmhYOsoZbg/src_client_secret_EVnN8bitF0wDIe6XGcZTThYZ");
const test3 = getSrcAndSecret("https://hooks.stripe.com/adapter/ideal/redirect/complete");
console.log(test1, test2, test3)

const url = "https://hooks.stripe.com/adapter/ideal/redirect/complete/src_1E2lmZHazFCzVZTmhYOsoZbg/src_client_secret_EVnN8bitF0wDIe6XGcZTThYZ?success=true";
const res = url.split(/\?|\//g).filter(el => el.startsWith("src"));
console.log(res)

const [a, b] = event.url.split("?")[0].split("/").slice(-2);

Related

how to convert string array of objects to array of objects

I have an array that I want to convert but I have no idea how to do it
how can i convert this array
const a = ['{/run:true}', '{/sleep:false}'];
in this array
const b = [{'/run':true}, {'/sleep':false}];
Using map and a regular expression:
const a = ['{/run:true}', '{/sleep:false}'];
const b = a.map(s => {
const [_,k,v] = s.match(/\{(.+):(.+)}/);
return {[k]: JSON.parse(v)};
});
console.log(b);
Or other way is to run a sting replacement and JSON.parse
const a = ['{/run:true}', '{/sleep:false}'];
const b = JSON.parse("[" + a.toString().replace(/\{([^:]+)/g, '{"$1"') + "]");
console.log(b);
Created this simple function to do exactly that
const a = ['{/run:true}', '{/sleep:false}'];
// desired output
const b = [{ run: true }, { sleep: false }];
const c = a.map(item => {
const key = item.match(/\w+/)[0];
const value = item.match(/true|false/)[0];
return { [key]: value === 'true' };
});
console.log(c);
const a = ['{/run:true}', '{/sleep:false}'];
const output = a.map(item => {
const normalize = item.replaceAll("{", "").replaceAll("}", "")
const splitedStr = normalize.split(':');
const key = splitedStr[0];
const value = splitedStr[1];
return {[key]: value}
})
console.log(output)
const a = ['{/run:true}', '{/sleep:false}'];
const c = a.map(item => {
return {
['/' + item.split(':')[1].split('{')[0]]: item.split(':')[1].split('}')[0]
};
});
console.log(c);

Parsing string with special character and returning the output

I know its a pretty simple question, but to anyone who is new to Javascript this can be interesting.
Is there any fastest way to parse this string and get the color for the fruit like shown below :
var fruitAndColors = "APPLE=RED&GUAVA=GREEN&STRAWBERRY=RED&BANANA=yellow&ORANGE=orange"
var applecolor = getColor("APPLE") // RED
var bananaColor = getColor("BANANA") //yellow
Here is a regex match approach:
function getColor(fruitAndColors, fruit) {
return fruitAndColors.match(new RegExp("\\b" + fruit + "=([^&]+)"))[1];
}
var fruitAndColors = "APPLE=RED&GUAVA=GREEN&STRAWBERRY=RED&BANANA=yellow&ORANGE=orange"
console.log(getColor(fruitAndColors, "APPLE")); // RED
console.log(getColor(fruitAndColors, "BANANA")); //yellow
For the case of searching for APPLE we use the following regex pattern:
\bAPPLE=([^&]+)
This places the key (the color) in the first capture group, which the helper function then returns.
Regex will probably be the best bet for this however it is definitely not my strong-suit. That said, here's what I came up with just some Javascript:
var fruitAndColors =
'APPLE=RED&GUAVA=GREEN&STRAWBERRY=RED&BANANA=yellow&ORANGE=orange';
const getColor = (key) => {
const entries = fruitAndColors.split('&').reduce((acc, val) => {
const [fruit, color] = val.split('=');
acc[fruit] = color;
return acc;
}, {});
return entries[key];
};
var appleColor = getColor('APPLE'); // RED
var bananaColor = getColor('BANANA'); //yellow
A little class that handle that kind of url parse
class UrlParse {
#objects;
constructor(uri) {
this.uri = uri
this.objects = {}
this.parse()
}
parse() {
let arr = this.uri.split('&')
for (let a of arr) {
let arr = a.split(/\=/)
this.objects[arr[0]] = arr[1]
}
}
getName(name) {
return this.objects[name]
}
}
var fruitAndColors = "APPLE=RED&GUAVA=GREEN&STRAWBERRY=RED&BANANA=yellow&ORANGE=orange"
let p = new UrlParse(fruitAndColors)
console.log(p.getName('BANANA'))
You can use a regular expression passing in the fruit, and returning the first match.
const fruitAndColors = 'APPLE=RED&GUAVA=GREEN&STRAWBERRY=RED&BANANA=yellow&ORANGE=orange';
console.log(getColor('APPLE', fruitAndColors));
console.log(getColor('GUAVA', fruitAndColors));
console.log(getColor('STRAWBERRY', fruitAndColors));
console.log(getColor('BANANA', fruitAndColors));
console.log(getColor('ORANGE', fruitAndColors));
function getColor(fruit, fruitAndColors) {
const regex = new RegExp(`${fruit}=([A-Za-z]+)`);
return fruitAndColors.match(regex)[1];
}
Why don't we just use a map instead of parsing it with regex. I think that would be more efficient.
const str = "APPLE=RED&GUAVA=GREEN&STRAWBERRY=RED&BANANA=yellow&ORANGE=orange";
const fruitColorArray = str.split("&").map((value) => value.split("="));
const fruitColorMap = new Map(fruitColorArray);
function getColor(fruit) {
return fruitColorMap.get(fruit);
}
const applecolor = getColor("APPLE"); // RED
const bananaColor = getColor("BANANA"); //yellow
console.log(applecolor, bananaColor);

how do I replace dynamic variables which are unknown dynamically

I have a .js file which has config structure something like this.
genGetLocations:{
data_url:'restaurants/{var1}/tables/{var2},
}
THis is one example. Some might have config that has data_url which has more than two dynamic variables. Then in .vue file, after getting the data_url, i will have two ids which have to be replaced into var1 and var2 so that I will have the final rest api url to make the request to.
Problem: I don't know how many variables each data_url is going to have and where they are going to be placed in data_url. So, in .vue files, when I will have the ids, i want to replace them in data_url.
Depending on whether your IDs are in an array or an object, you could do one of the following:
const data = 'restaurants/{var1}/tables/{var2}';
const idsArray = [101, 102];
console.log(
data.replace(/\{var(\d+)\}/g, (substr, idx) => idsArray[parseInt(idx) - 1])
);
const data = 'restaurants/{var1}/tables/{var2}';
const idsObj = {
var1: 101,
var2: 102
};
console.log(
data.replace(/\{(var\d+)\}/g, (substr, key) => idsObj[key])
);
If you want the keys to be arbitrary:
const data = 'restaurants/{foo}/tables/{bar}';
const idsObj = {
foo: 101,
bar: 102
};
console.log(
data.replace(/\{(.*?)\}/g, (substr, key) => idsObj[key])
);
This is looking for every {} in your URL. So it could be {var1}, {string2} or so.
Try this:
var info = {"genGetLocations":{
"data_url" : "restaurants/{var1}/tables/{var2}"
}};
var ids = ["test1", "test2", "test3"];
var regexp = /\{.*?\}/g;
var results = info.genGetLocations.data_url.match(regexp);
var replacedString = info.genGetLocations.data_url;
results.forEach(function(result, index) {
replacedString = replacedString.replace(new RegExp(result,"g"), ids[index]);
});
console.log(replacedString);
May be you can try this
String.prototype.formatUnicorn = String.prototype.formatUnicorn || function () {
var e = this.toString();
if (!arguments.length)
return e;
var t = typeof arguments[0],
n = "string" == t || "number" == t ? Array.prototype.slice.call(arguments) : arguments[0];
for (var i in n)
e = e.replace(new RegExp("\\{" + i + "\\}", "gi"), n[i]);
return e
}
/** Lets Assume your Code
genGetLocations:{
data_url:'restaurants/{var1}/tables/{var2},
}**/
console.log('restaurants/{var1}/tables/{var2}'.formatUnicorn({'var1':'test1','var2':'test2'}))

JavaScript convert string to object contains ":"

I have the following string var xx = "website:https://google.com"; I'm trying to convert to dictionary {website:"https://google.com"} usually I use str.split(":") but here I have multi : I can use replace function but what is the best way to do that ?
const strToDictionary = kColonV => {
const tmpArray = kColonV.split(':')
const k = tmpArray.shift()
const v = tmpArray.join(':')
return {[k]:v}
}
var xx = "website:https://google.com";
strToDictionary(xx) // Object { website: "https://google.com" }
Or, perhaps just:
const toDictonary = str => { return {[str.split(':')[0]]:str.substr(str.indexOf(':')+1)} }
toDictionary(xx) // Object { website: "https://google.com" }
There's a lot of ways you could phrase this.
class Dictionary extends Object {};
const kvToDict = str => Dictionary.assign( // No need to do this, but it's interesting to explore the language.
new Dictionary(),
{[str.slice(0, str.indexOf(':'))]:str.slice(str.indexOf(':')+1)}
)
const kvDict = kvToDict("website:https://google.com")
console.log(kvDict.constructor, kvDict) // Dictionary(), { website: "https://google.com" }
I like this one:
const kvToObj = str => Object.assign(
{},
{[str.slice(0, str.indexOf(':'))]:str.slice(str.indexOf(':')+1)}
)
kvToObj("website:https://google.com") // Object { website: "https://google.com" }
You can split on the first occurrence of :.
var xx = "website:https://google.com";
xx = xx.split(/:(.+)/);
var dictionary = {[xx[0]]:xx[1]};
console.log(dictionary);

How to extract page category and variable names into array from URL in Javascript

I have a link like this:
https://example.com/category?variable1=value1&variable2=value2
and I need to extract page category and variable names and save it into variable and into array of variable names:
category = "category";
array = ["variable1", "variable2"];
Any sugestions how can I achieve it using Javascript?
If your link is a string like the one you reported a simple solution can be based on:
str.split([separator[, limit]]) where as separator you can use a regex
array.splice(start, deleteCount) in order to remove the first and last ele
The example:
var str = 'https://example.com/category?variable1=value1&variable2=value2';
var res = str.substr(str.lastIndexOf('/') + 1).split(/[?]|=[^&]*&{0,1}/);
var category = res[0];
var arr = res.splice(1, res.length - 2);
console.log(category);
console.log(arr);
If an object works for you as well here is a solution:
//Get variables into an object
function uriToJson (url) {
const regx = /(\?|&)([^=]+)=([^&]+)/g;
const index = url.search(regx) + 1;
const params = url.substring(index);
return JSON.parse(`{"${decodeURI(params)
.replace(/"/g, '\\"')
.replace(/&/g, '","')
.replace(/=/g, '":"')}"}`);
}
const url = 'https://example.com/category?variable1=value1&variable2=value2'; //window.location.href...
const obj = uriToJson(url);
console.log(obj);
//Get category into a variable
var stepone = url.substring(0,url.indexOf('?'));
var steptwo = stepone.substring(stepone.indexOf('m/') + 1 )
var category = steptwo.replace('/','');
console.log(category);

Categories