Get url after slash javascript

Exploding an url in javascript can be done using the official rfc2396 regex:

var url = "http://www.example.com/path/to/something?query#fragment";
var exp = url.split(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/);

This will gives you:

["", "http:", "http", "//www.example.com", "www.example.com", "/path/to/something", "?query", "query", "#fragment", "fragment", ""]

Where you can, in your case, easily retrieve you path with:

const path = exp[5];

And therefore the first word after the path using:

const rootPath = path.split('/')[1];

JavaScript can access the current URL in parts. For this URL:

https://css-tricks.com/example/index.html?s=flexbox
  • window.location.protocol = “http:”
  • window.location.host = “css-tricks.com”
  • window.location.pathname = “/example/index.html”
  • window.location.search = “?s=flexbox”

So to get the full URL path in JavaScript:

var newURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname + window.location.search

A bit of a more modern way of working with URLs is the URL() global method.

If you need to break up up the pathname, for example, a URL like https://css-tricks.com/blah/blah/blah/index.html, you can split the string on “/” characters

var pathArray = window.location.pathname.split('/');

Then access the different parts by the parts of the array, like

var secondLevelLocation = pathArray[0];

To put that pathname back together, you can stitch together the array and put the “/”‘s back in:

var newPathname = "";
for (i = 0; i < pathArray.length; i++) {
  newPathname += "/";
  newPathname += pathArray[i];
}

Probably the quickest way to take a peak at what you have is to put window.location in the DevTools console and see:

Get url after slash javascript


To split a URL, use the split() method. Use toString() before that. Let us see an example

Example

var newURL="http://www.example.com/index.html/homePage/aboutus/";
console.log(newURL);
var splitURL=newURL.toString().split("/");
console.log(splitURL);

Above, we have set forward slash in the split() function, since we need to split the URL after every such slash.

To run the above program, you need to use the following command −

node fileName.js.

Output

Here, my file name is demo150.js. This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo150.js
http://www.example.com/index.html/homePage/aboutus/[
   'http:',
   '',
   'www.example.com',
   'index.html',
   'homePage',
   'aboutus',
   ''
]

Get url after slash javascript

Updated on 11-Sep-2020 08:36:01

  • Related Questions & Answers
  • How to replace before first forward slash - JavaScript?
  • Possible to split a string with separator after every word in JavaScript
  • Moving every alphabet forward by 10 places in JavaScript
  • Select text after last slash in MySQL?
  • Squaring every digit of a number using split() in JavaScript
  • Why should we use a semicolon after every function in JavaScript?
  • JavaScript Insert space after every two letters in string?
  • Do I need to use a semicolon after every function in JavaScript?
  • JavaScript - Redirect a URL
  • JavaScript example for Capturing mouse positions after every given interval
  • MySQL query to split a column after specific characters?
  • Kth smallest element after every insertion in C++
  • Replace() with Split() in JavaScript to append 0 if number after comma is a single digit
  • Java regex program to split a string at every space and punctuation.
  • Writing a custom URL shortener function in JavaScript

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    The task is to get the string after a specific character(‘/’). Here are few of the mostly used techniques discussed. We are going to use JavaScript.
    Approach 1:

    • Split the string by .split() method and put it in a variable(array).
    • Use the .length property to get the length of the array.
    • From the array return the element at index = length-1.

    Example 1: This example using the approach discussed above.

    <html>

    <head>

        <title>

            Get value of a string

          after last slash in JavaScript?

        title>

    head>

    <body style="text-align:center;"

          id="body">

        <h2 style="color:green;">  

                GeeksForGeeks  

            h2>

        <p id="GFG_UP" 

           style="font-size: 15px;

                  font-weight: bold;">

        p>

        <button onclick="GFG_FUN()">

            click here

        button>

        <p id="GFG_DOWN" 

           style="font-size: 24px; 

                  font-weight: bold;

                  color: green;">

        p>

        <script>

            var el_up = document.getElementById("GFG_UP");

            var el_down = document.getElementById("GFG_DOWN");

            var str = "folder_1/folder_2/file.html";

            el_up.innerHTML = "Click on the button to get"+

              " the string after last slash.<br><br>String - '"

            + str + "'";

            function GFG_FUN() {

                str = str.split("/");

                el_down.innerHTML = str[str.length - 1];

            }

        script>

    body>

    html>

    Output:

    Approach 2:

    • First, find the last index of (‘/’) using .lastIndexOf(str) method.
    • Use the .substring() method to get the access the string after last slash.

    Example 2: This example using the approach discussed above.

    <html>

    <head>

        <title>

            Get value of a string 

          after last slash in JavaScript?

        title>

    head>

    <body style="text-align:center;" 

          id="body">

        <h2 style="color:green;">  

                GeeksForGeeks  

            h2>

        <p id="GFG_UP"

           style="font-size: 15px;

                  font-weight: bold;">

        p>

        <button onclick="GFG_FUN()">

            click here

        button>

        <p id="GFG_DOWN" 

           style="font-size: 24px; 

                  font-weight: bold;

                  color: green;">

        p>

        <script>

            var el_up = document.getElementById("GFG_UP");

            var el_down = document.getElementById("GFG_DOWN");

            var str = "folder_1/folder_2/file.html";

            el_up.innerHTML = "Click on the button to get"+

              " the string after last slash.<br><br>String - '"

            + str + "'";

            function GFG_FUN() {

                el_down.innerHTML = 

                  str.substring(str.lastIndexOf('/') + 1);

            }

        script>

    body>

    html>

    Output:


    How do I get the value of a URL after a slash?

    Use the . substring() method to get the access the string after last slash.

    How to get URL path in JavaScript?

    window.location.href returns the href (URL) of the current page. window.location.hostname returns the domain name of the web host. window.location.pathname returns the path and filename of the current page.

    How to split URL by slash JavaScript?

    “javascript split url last slash” Code Answer's.
    var str = "var1/var2/var3";.
    var rest = str. substring(0, str. lastIndexOf("/") + 1);.
    var last = str. substring(str. lastIndexOf("/") + 1, str. length);.
    console. log(rest);.
    console. log(last);.

    How do I get the current URL?

    Answer: Use the window. location. href Property location. href property to get the entire URL of the current page which includes host name, query string, fragment identifier, etc.