Grabbing a slug from a URL using JavaScript

I have examples of different URLs.

Now, I aim to extract specific strings from these URLs.

'about'
'product'
'learn'

I've attempted this using Next.js.

import { useRouter } from 'next/router'

const { asPath } = useRouter()

const result = asPath.substring(1).split('?')[0].split('#')[0].split('/')[0]

Is there a more efficient approach, such as utilizing RegEx or other techniques?

Additionally, I am interested in achieving the following outcomes:

'about' or ['about']
'product/roller' or ['product','roller']
'learn/goin' or ['learn','goin']

Is that feasible?

Answer №1

To create a new object for the URL, you can utilize the pathname and extract characters that are not slashes

let slug = url => new URL(url).pathname.match(/[^\/]+/g)

console.log(slug('https://example.com/about?hl=en#iron'))
console.log(slug('https://example.com/product/roller/?hl=en&lo=true'))
console.log(slug('https://example.com/learn/goin/?hl=en&lo=true#iron'))

An alternative method without using regex is

.pathname.split('/').filter(Boolean)

Answer №3

Even though the question is not about URLs, it's worth noting that the URLs you're using consist of parameters. These parameters should be retrieved using URLSearchParams or searchParams:

let params = (new URL(document.location)).searchParams;
let hl = params.get('hl');
let lo = params.get('lo');

Please refer to MDN documentation for more information.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Only when all the AJAX scripts have finished executing should you refresh the page

As I endeavor to initiate various actions upon clicking a button .button, my first task is to cleanse each <div> that contains the class .classToClean and subsequently run ajax scripts to update the database. To accomplish this, I have opted for the ...

AngularJS - Refreshing Controller when Route Changes

Scenario app.controller('headerController', ['$scope', '$routeParams', function($scope, $routeParams) { $scope.data = $routeParams; }]); app.config(['$routeProvider', function ($routeProvider) { ...

What is the best way to transfer an item from one object to another within the same array using javascript?

I'm dealing with an array structure like the following: [ { "ID": 227886, "post_author": "54" }, { "ID": 227545, "post_author": &q ...

Learn how to trigger a re-render in React to update a value stored in local storage

I need assistance in displaying a spinner with a percentage value during file uploads within my React application. To achieve this, I am utilizing Material UI's circular progress. My approach involves making a REST call using Axios to obtain the perce ...

Automatic line breaks within a JavaScript code can be achieved by using

I need help formatting this text: hello everyone. My name is PETER. hahahah ahahah .... If I have a fixed width, how can I automatically line break the text to look like this: hello everyone. My name is PETER. hahahah ahahah ...

Clerk Bug: The UserResource type returned by useUser() does not match the @clerk/types

When attempting to pass the user obtained from useUser(), an error occurred: The 'UserResource' type is lacking the required properties 'passkeys' and 'createPasskey' from the 'UserResource' type Upon investigating ...

Creating a collapsible sidebar feature in Angular 2

Currently in the process of converting an HTML jQuery AdminLTE dashboard to Angular 2 In the past, I would hide and show the sidebar using toggle() in jQuery. Now I'm wondering how to achieve the same functionality in Angular 2. I am utilizing the ...

Utilizing AngularJS for Showcasing JSON Information Using Ng-Repeat and Ng-Factory

As a newcomer to Javascript and Angular, I am currently working on integrating AngularJS into my website. Despite watching tutorials from CodeSchool, Egghead, and others, I seem to be stuck at the very beginning. My issue lies in retrieving JSON data from ...

What sets apart !$scope.variableName from $scope.variableName in AngularJS?

Greetings to all my fellow coders! As a newcomer in the field, I often find myself pondering over things like this. Would someone be kind enough to elucidate the dissimilarity between these two elements in AngularJs? $scope.variableName and !$scope.var ...

Updating the progress bar without the need to refresh the entire page is

Currently, I have two PHP pages: page.php and loader.php. Loader.php retrieves data from MySQL to populate a progress bar, while page.php contains a function that refreshes loader.php every second. This setup gets the job done, but it's not visually a ...

As I attempt to connect with the bitcoin average server, I encounter a 403 status code error in the communication

const express = require("express"); const bodyParser = require("body-parser"); const request = require("request"); const app = express(); app.use(bodyParser.urlencoded({extended: true})); app.get("/", function(req, res){ res.sendFile(__dirname + "/inde ...

How to bind array elements in Vue.js

I am currently working with an array that contains various arrays and properties within it. My goal is to iterate through the array and generate new rows for each item in it. Here is a snippet of what I have been working on: var orderDetails = [ ...

The direction to the Excel document for conversion into JSON

I have a project in progress where I'm currently working on converting an Excel sheet to JSON. Once the data is converted, it will be displayed using jQuery Datatables on the browser. My code is functioning as expected, but I am encountering an issue ...

Prevent user input in Vue.js until the value has been modified

Need help handling initial input values: <input type="text" v-model="name" ref="input" /> <button type="submit" :disabled="$refs.input.defaultValue == $refs.input.value">Submit</button> Encountering an error with the disabled binding: C ...

Tips on organizing and designing buttons within a canvas

let canvas = document.getElementById("canvas"); let context = canvas.getContext("2d"); // for canvas size var window_width = window.innerWidth; var window_height = window.innerHeight; canvas.style.background="yellow" canvas.wid ...

Extract an array from a JSON array based on the lowest value of the keys

Consider the following array: [{ "activity" : "Hiking", "level" : "8.5" }, { "activity" : "Swimming", "level" : "-3.2" }] I want to loop through the JSON data and identify the object with the lowest value for level. In this example, I sho ...

Is there a way to stop "window.location.replace()" from being replaced or overridden?

Is there a method to safeguard against alterations or overrides of window.location.replace()? For instance, attempting to change it like this: window.location.replace = function(){ return "Hi" }. Initially, I experimented with using Object.free ...

Is it considered acceptable to utilize a v-model's value as the basis for an if-statement?

How can I incorporate the v-model="item.checked" as a condition within the validations() function below? <table> <tr v-for="(item, i) of $v.timesheet.items.$each.$iter" > <div> <td> ...

Handling multiple render calls and rerenders in React function components with setTimeout (best practice for firing multiple times)

Is there a way to optimize the Notification component in my App, so that the setTimeout function is only initialized once even if multiple notifications are pushed into the state? function Notification(props) { console.log("Notification function compone ...

Automatically send users to the login page upon page load if they are not authenticated using Nuxt and Firebase

I'm currently facing an issue with setting up navigation guards in my Nuxt application. The goal is to redirect users to the login screen if they are not authenticated using Firebase Authentication. While the router middleware successfully redirects u ...