Discovering the final segment of a URL using AngularJS

Is there a way to create a function in AngularJS that can check the last segment of a URL?

Here are some examples:

#/menu1/123/edit

#/menu2/444/create/new

#/menu3/submenu1/333/create/new

#/menu4/submenu2/subsubmenu1/subsubsubmenu1/543/edit

The key points here are:

123, 444, 333, and 543 are IDs generated externally outside of Angular

The goal is to validate the last segments of the URLs: /edit or /create/new.

The length of the URL may vary (depending on the number of slashes inside).

In my Angular controller, I have code to retrieve the URL:

.controller('urlCtrl', ['$scope', '$rootScope', '$location', function ($scope, $rootScope, $location) {

    $rootScope.location = $location;
    $scope.hashPath = "#" + $rootScope.location.path().toString();
}]);

I'm appending the # symbol to the URL for comparison with JSON later on.

I attempted this proposed solution without success (tried other solutions from the thread as well).

Any insights or suggestions?

EDIT:

Alternatively, how can we specifically check for edit or create within the URL?

My approach so far is:

var path = $location.path();
var multisearch = path.search(/create|edit|new/);
console.log("multisearch: " + multisearch);

Answer №1

Here is the code snippet that will provide the outcome you are looking for:

window.alert(window.location.href.substr(window.location.href.lastIndexOf('/') + 1));

To retrieve the current URL, simply utilize: window.location.href Afterwards, extract the portion following the final '/' character.

Answer №2

A more streamlined approach:

const getLastDirectory = () => {
  return location.pathname.split('/').slice(-1)[0];
}

For example, in the URL

http://example.com/firstdir/seconddir/thirddir?queryparams#hash
, this function will return thirddir.

  • The pathname variable stores everything after the domain name and before any query parameters.
  • Using split breaks up the URL into an array separated by forward slashes (/).
  • slice extracts only the last item in the array.
  • Finally, accessing index [0] returns this last item as a string rather than an element of an array.

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

The AngularJS element fails to display on the screen

I am currently learning AngularJS and I am struggling to understand how components are linked to the view in the tutorial. I have created a component that is quite similar: angular.module('phonecatApp').component('nameList', { temp ...

The ZIP file downloaded from NodeJS is corrupted and cannot be opened

Currently, I am utilizing the following code to create a MySQL dump in memory, then zip that SQL file with a password from memory and save it to the hard drive so it can be streamed to the client... /* DUMP - database */ var mysqld ...

How to implement a form in PHP that doesn't refresh the page upon submission

I am having an issue with this ajax code. I know it works, but for some reason it's not submitting. <script type="text/javascript"> $(function(){ $('input[type=submit]').click(function(){ $.ajax({ type: "POST", ...

What is the best way to make one div show that another div is being toggled in a slideshow display?

I am searching for a solution to indicate when a div is being toggled, using a separate div with the class of ".bars". Experimented with if statements and modifying classes on the indicator div ".bars" to adjust its characteristics... The ".bars" indicat ...

Creating mathematical formulas in JavaScript

How can the equation be translated into JavaScript? This is the proposed programming solution, but there seems to be an issue. var MIR = parseFloat(($('#aprrate').val() / 100) / 12); var paymentAmount = (MIR * $('#amounttofinance').va ...

In React js, automatically insert a new row into a table once the Dialog window has

I am currently exploring Reactjs and using Material UI Dialog to implement a dialog box for users to input information and interact with a POST API. After the process is completed, the dialog closes but I would like to dynamically display the added informa ...

Having trouble receiving a JSON array after making an Ajax request

I have read through previous posts on this issue, but I still can't seem to figure it out. Hopefully, someone here can help me solve this problem. My challenge lies in retrieving an array, which I have encoded in json, from a PHP script and passing i ...

Implement a unique combination of texture and color on a cube using three.js

In my three.js project, I aim to design a cube with both texture and color simultaneously. The cubes need to have the ability to change color when selected, hence it is crucial that they possess a base color. I wonder if overlaying a black and white text ...

What is the process for downloading and installing angular-cli on a Windows 7 operating system

Trying to install angular-cli on Windows has been a challenge for me. Despite running the command npm install -g angular-cli, I encountered an error when trying to use ng new afterwards. The system would not recognize the "ng" command, even after checking ...

Choose a specific element based on the content of its href attribute

Hello and thank you for your assistance! In the past, I have used JavaScript to add an active class to an element based on the URL being displayed. Now, I am looking to modify this behavior. My goal is to add an active class to an element if the href att ...

three.js canvas, sphere rotates gracefully to the right

Trying to get the sphere to turn right at a very slow pace. Here is my source code: I have created a new container with canvas inside, you can view the code below. How can I make the sphere turn slowly? You can also check out my git repository on github: s ...

Issue with caching: Browser cache not being utilized even after implementing Cache-Control Header

First Requesthttps://i.sstatic.net/xtJCW.png Second Inquiryhttps://i.sstatic.net/4R9ln.png I have implemented a node module(express-cache-ctrl) to activate caching on a proxy. app.use(cache.public(3600)); Despite having Cache-control headers with max-age ...

Issue with THREE.meshphongmaterial: Causing Objects to Appear Black

Attempting to implement THREE.meshphongmaterial from a tutorial found at: Encountering issues as it is resulting in a black color. Link to the jsfiddle code: http://jsfiddle.net/8hrk7mu6/12/ The problem seems to be on line 32: var material = new THREE.M ...

The element type is not valid: it should be a string for built-in components or a class/function for composite components, but it is currently an object in a React project

In the process of developing a React app to explore MUI capabilities, I encountered an error in my browser: The issue reported is: Element type is invalid - expected a string (for built-in components) or a class/function (for composite components), but rec ...

Unlocking the potential of the Route component within the children of the useRoutes hook

Currently, I am utilizing the useRoutes hook to configure my app routes as it offers a cleaner setup compared to using the traditional Routes and Route components. However, I encountered an issue when attempting to include a Route component within one of m ...

Difficulty encountered when attempting to modify textures in three.js

Trying to apply a texture to a mesh in three.js: Initializing variables: var container, stats; var camera, scene, projector, raycaster, renderer; var mouse = new THREE.Vector2(), INTERSECTED; onMouseDownMouseX = 0, onMouseDownMouseY ...

Which approach yields better performance: setting all dom events simultaneously, or incrementally?

Is it more effective to attach event listeners permanently or only when needed? For example, consider a scenario where you have a dropdown menu in your HTML that opens when clicked. Within this menu, there is a close button that closes the menu upon click ...

Use jQuery or javascript to eliminate the 'Webpage Dialog' from the 'showModalDialog' window

At one point on the page, I have a line of code that looks like this: onclick="window.showModalDialog("http://rauf-thecoder.blogspot.com/");" When executed, it displays the following: Is there a way to eliminate the title bar text for the Webpage Dialog ...

Error API0005 has occurred due to an invalid signature connection when trying to establish a connection between Google Apps Script

Currently, I am attempting to showcase various data points from my BitStamp account on a Google Spreadsheet. To accomplish this task, the Google Apps Script (GAS) that utilizes JavaScript is being utilized. The issue at hand involves an error with code AP ...

Manipulating object information within a nested for loop

I have a variable called jobs in my scope, which is an array containing objects for each department along with their respective data. [ “Accounting”: { “foo” : “foo”, “bar” : "bar" }, “Delivery”: { ...