Best way to get the pathname from string - javascript

I am trying to get the first segment of the path from a string.
Current Behaviour:
const pathOne = '/tasks/123456789';
const pathTwo = '/tasks';
const pathThree = '/tasks?name=Doe';
const resultOne = pathOne.split('/')[1];
const resultTwo = pathTwo.split('/')[1];
const resultThree = pathThree.split('/')[1];
console.log(resultOne, resultTwo, resultThree);
As you see in the above code, I tried split the string and get second element from the array which has the first segment of the path.
But unfortunately in the last one, I get query params along with it, which I intend to remove it and get only tasks for all three strings.
Kindly please help me with efficient way of achieving the result that gives only the first segment of the path and ignore query params.
Note:
Please don't consider it as url and it is just a normal string with pathname and I am intend to get only the first segment of it tasks .

You can do somethong like this
const pathOne = '/tasks/123456789';
const pathTwo = '/tasks';
const pathThree = '/tasks?name=Doe';
const getFile = fullPath => {
const [path, query] = fullPath.split('?')
return path.split('/')[1]
}
console.log(getFile(pathOne));
console.log(getFile(pathTwo));
console.log(getFile(pathThree));

You have index key after .split() -> [1]. When you have key index, you told "Give me first separated word from string"
If you remove it, you can get every string separated by "/". Try :)
const pathOne = '/tasks/123456789';
const pathTwo = '/tasks';
const pathThree = '/tasks?name=Doe';
const resultOne = pathOne.split('/');
const resultTwo = pathTwo.split('/');
const resultThree = pathThree.split('/');
console.log(resultOne, resultTwo, resultThree);
EDIT: IF you don't wanna query parameters, you must split "pathThree" string also by "?"

If you're getting the string from the window object you can obtain the pathname from the window.location property
const pathParts = window.location.pathname.split('/');
Otherwise you can construct an URL object
const myUrl = new URL('https://www.example.com/get/the/pathname?param=1&param=2');
const pathParts = myUrl.pathname.split('/');
If you're working on a path string (not a valid url) I'd suggest something like
const myStr = '/get/the/pathname?paramA=1&paramB=2';
const parts = myStr.split('?')[0].split('/');

enter code hereconst pathOne = '/tasks/123456789';
const pathTwo = '/tasks';
const pathThree = '/tasks?name=Doe';
const resultOne = pathOne.split('/')[1];
const resultTwo = pathTwo.split('/')[1];
const resultThree = pathThree.split(/[/?_]+/)[1];
console.log(resultOne, resultTwo, resultThree);

Related

JavaScript: How to get first parameter, actually first key from URL?

I am trying to get first key from URL, like this:
const currentUrl = window.location.href;
const parmsFromUrl = new URLSearchParams(currentUrl);
const paramToCheck = parmsFromUrl.keys[0];
But constantly I get undefined, can someone tell how me how to get only first parameter, not a value, I just want key? Thanks.
With URLSearchParams you have to use window.location.search
With URL you have to use window.location.href
const currentUrl = window.location.search;
const parmsFromUrl = new URLSearchParams(currentUrl);
URLSearchParams.keys() returns an iterator, so you have to use next() to get first value
const paramToCheck = parmsFromUrl.keys().next().value;

How to replace this url to my a format id that i want, thanks [duplicate]

This question already has an answer here:
Reference - What does this regex mean?
(1 answer)
Closed 2 years ago.
Is there any way (maybe a regex) to replace the id dynamic to "id"
I use js and typescript
The original url:
localhost:4200/reservations/5eda023aed43c1e46d6ce804/properties/5ca199fdda8ba619695b5728
The url i want:
localhost:4200/reservations/id/properties/id
Here's a solution using regex:
function replaceURL(url, data) {
Object.entries(data).forEach(([key, value]) => url = url.replace(new RegExp(`(?<=${key}\\/)\\w+`, 'g'), value));
return url;
}
// the original url
const url = 'localhost:4200/reservations/5eda023aed43c1e46d6ce804/properties/5ca199fdda8ba619695b5728';
// put what you want to replace in this object
const data = {
reservations: 'id',
properties: 'id'
};
const result = replaceURL(url, data);
console.log(result);
Edit
I think I overthought the situation, if you just want to replace the text similar to 5eda023aed43c1e46d6ce804, you can just use the following regex:
/(?<=\/)[0-9a-f]{24,}/g
const regex = /(?<=\/)[0-9a-f]{24,}/g;
let url = 'localhost:4200/reservations/5eda023aed43c1e46d6ce804/properties/5ca199fdda8ba619695b5728';
let result = url.replace(regex, 'id');
console.log(result);
url = 'http://localhost:4200/minibar/items/5efdcee02c37c160e8a5bbe1';
result = url.replace(regex, 'id');
console.log(result);
You can try this
let url = 'localhost:4200/reservations/5eda023aed43c1e46d6ce804/properties/5ca199fdda8ba619695b5728';
let replacedUrl = url.replace(/\/[a-fA-F0-9]{24}/g, "/id");
console.log(replacedUrl);
If your url format is fix then you can use this simple code.
var link=" localhost:4200/reservations/5eda023aed43c1e46d6ce804/properties/5ca199fdda8ba619695b5728";
//var link="http://localhost:4200/minibar/items/5efdcee02c37c160e8a5bbe1"
var hasNumber = /\d/;
var linkParts=link.split("/");
var i=link.indexOf("http")==0?3:2;
for(i;i<linkParts.length;i++)
{
if(linkParts[i].length>20 && hasNumber.test(linkParts[i]))
linkParts[i]="id";
}
document.write(linkParts.join("/"));
You can simply replace the exact id with what you want.
let url = 'localhost:4200/reservations/5eda023aed43c1e46d6ce804/properties/5ca199fdda8ba619695b5728';
let id = '5eda023aed43c1e46d6ce804' // the id to replace
let rx = new RegExp(id,"g"); // use "g" to indicate it should should ALL ids in the string
url = url.replace(rx, "id") // this will replace the dynamic id with the word "id"
// localhost:4200/reservations/id/properties/id

Best way to pass some variable/id through google cloud functions child?

How to get this running ? Need to pass the itens id in the path to have access to product node, how can I do this ?
const itens = db.ref();
const eanRef = itens.child('cart').child('itens/{id}').child('product');
To replace the value of an integer variable id to a string itens/{id} you can do the following:
var id = 15;
const itens = db.ref();
const eanRef = itens.child('cart').child('itens/'+id.toString()).child('product');
Use javascript template literals.
const id = 'id-whatever'
const itens = db.ref();
const eanRef = itens.child('cart').child(`itens/${id}`).child('product');

Returning an entire item in an arrray containing a specific value

I'm trying to get an item in array which contains a specific value.
Let's say I have an array
var arr = ["boat.gif", "goat.png", "moat.jpg"];
And I have a variable var imageName = "boat"
Since I do not know the file extension of imageName, I need a way to run it through my array and get "boat.gif" as the output.
I tried this with regular expressions
let filesString = arr.join(" ");
let regExName = new RegExp(imageName, "i");
let fileName = regExName.exec(filesĀ­String),
file = fileName.input.substĀ­r(fileName.index, 5);
It works but I'm hoping there's a better way
I hope this makes sense
Might be easier to filter by .includes or .startsWith instead:
var arr = ["boat.gif", "goat.png", "moat.jpg"];
var imageName = "boat";
const found = arr.find(str => str.includes(imageName));
console.log(found);
or
var arr = ["boat.gif", "goat.png", "moat.jpg"];
var imageName = "boat";
const found = arr.find(str => str.startsWith(imageName));
console.log(found);
If there might be other files in the directory which start with the same word (like boats.gif), then construct a regular expression like you're doing, but lookahead for a .:
var arr = ["boat.gif", "goat.png", "moat.jpg"];
var imageName = "boat";
const pattern = new RegExp(imageName + '(?=\.)');
const found = arr.find(str => pattern.test(str));
console.log(found);

JSON route matching via regex

Consider I have following JSON object
var urls = {
"GET/users/:id":1,
"POST/users":0
}
and if I have string "GET/users/10". How can I use this as key to get the value from urls JSON i.e. "GET/users/10" should match "GET/users/:id".
I don't want to iterate urls JSON and use regex for every key.
Is there a way to access JSON object using regex?
Thanks in advance.
Here is something that should work for you. I took some of the pieces from the Durandal router's RegEx matching logic which basically dynamically creates a regular expression object based on a defined route string and then tests with it against a passed string.
Here is the working example:
var urls = {
"GET/users/:id": 1,
"POST/users": 0
}
const getRouteRegExp = (
routeString,
routesAreCaseSensitive = false,
optionalParam = /\((.*?)\)/g,
namedParam = /(\(\?)?:\w+/g,
splatParam = /\*\w+/g,
escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g
) => {
routeString = routeString.replace(escapeRegExp, '\\$&')
.replace(optionalParam, '(?:$1)?')
.replace(namedParam, function(match, optional) {
return optional ? match : '([^\/]+)';
})
.replace(splatParam, '(.*?)');
return new RegExp('^' + routeString + '$', routesAreCaseSensitive ? undefined : 'i');
}
const getRouteByString = (string) => {
var resultArr = Object.entries(urls).find(([k, v]) => {
var regEx = getRouteRegExp(k)
return regEx.test(string)
}) || []
return resultArr[0]
}
console.log(getRouteByString('GET/users/10'))
console.log(getRouteByString('POST/users'))
console.log(getRouteByString('POST/users2'))
So what you have is the getRouteRegExp function which is the main thing here which would compose a regular expression object based on a passed route.
After that we go and for each existing route defined in urls we create one RegExp and try to match it against the provided string route. This is what the find does. If one is found we return it.
Since we are doing Object.entries we return the 0 index which contains the result.
Since this comes straight from the Durandal bits it supports all the route expressions that are built in Durandal ... like:
Static route: tickets
Parameterized: tickets/:id
Optional Parameter: users(/:id)
Splat Route: settings*details
You can read more about Durandal Router here
From your question what I can understand is your key is dynamic, so you can do something like this:
var urls = {
"GET/users/:id":1,
"POST/users":0
}
let id = 10
const yourValue = urls["GET/users/" + id]
You can use this code to
var urls = {
"GET/users/:id":1,
"POST/users":0
}
var regex = /"([^"]+?)"\s*/g;
var urlsJson = JSON.stringify(urls);
let result = regex.exec(urlsJson)
if(result && result.length > 0) {
var keyJson = result[1];
var value = urls[keyJson]
console.log('value', value)
}
Try Something like this:
const urls = (id) => ({
[`GET/users/${id}`]:1,
"POST/users":0,
});
console.log(urls(2));
I hope it may be helpful.
The json would look fine, just do a replace on the url, so replace the ending integer with :id and then you have the key by which you can directly access the value in the json.
So:
var url = "GET/users/10";
var urls = {
"GET/users/:id":1,
"POST/users":0
}
url = url.replace(/users\/\d+/, 'users/:id');
console.log(urls[url]);
Do as many replaces on the url to convert all possible url's to the keys in your json.

Categories

Resources