How to split a url in javascript?

I have constructed a url path that are pointing to different hostname www.mysite.com, so for example:

var myMainSite = 'www.mymainsite.com' + '/somepath';

so this is equivalent to www.mymainsite.com/path/path/needthispath/somepath.

How I'm doing it now is like the code below and this gives me a bunch of indexes of the url in the console.log.

var splitUrl = myMainSite.split('/');

console.log looks like:

0: http://
1: www.
2: mysite.com
3: path
4: path
5: needthispath
6: somepath

and I concat them like splitUrl[5]+'/'+splitUrl[6] and it doesn't look pretty at all.

So my question is how to split/remove url location http://www.mymainsite.com/ to get the url path needthispath/somepath in js? Is there a quicker and cleaner way of doing this?


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',
   ''
]

How to split a url in 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

Last update on August 19 2022 21:51:52 (UTC/GMT +8 hours)

JavaScript Basic: Exercise-144 with Solution

Write a JavaScript program to break an address of an url and put it's part into an array.

Note: url structure : ://.org[/] and there may be no part in the address.

Pictorial Presentation:

How to split a url in javascript?

Sample Solution:

HTML Code:




  
  
  Break an address of an url and put it's part into an array.






JavaScript Code:

function break_address(url_add) {
    var data = url_add.split("://")
    var protocol = data[0];
    data = data[1].split(".com");
    var domain = data[0];
    data = data[1].split("/");

    if(data[1]){
        return [protocol,domain,data[1]]
    }

    return [protocol,domain]
}

var url_add = "https://www.w3resource.com/javascript-exercises/"
console.log("Original address: "+url_add)
console.log(break_address(url_add))

Sample Output:

Original address: https://www.w3resource.com/javascript-exercises/
["https","www.w3resource","javascript-exercises"]

Flowchart:

How to split a url in javascript?

ES6 Version:

function break_address(url_add) {
    let data = url_add.split("://");
    const protocol = data[0];
    data = data[1].split(".com");
    const domain = data[0];
    data = data[1].split("/");

    if(data[1]){
        return [protocol,domain,data[1]]
    }

    return [protocol,domain]
}

var url_add = "https://www.w3resource.com/javascript-exercises/"
console.log(`Original address: ${url_add}`)
console.log(break_address(url_add))

Live Demo:

See the Pen javascript-basic-exercise-144 by w3resource (@w3resource) on CodePen.

Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to sort the strings of a given array of strings in the order of increasing lengths.
Next: Write a JavaScript program to find the maximum integer n such that 1 + 2 + ... + n <= a given integer.

JavaScript: Tips of the Day

An async function

async function getData() {
  return await Promise.resolve('I made it!');
}

const data = getData();
console.log(data);

An async function always returns a promise. The await still has to wait for the promise to resolve: a pending promise gets returned when we call getData() in order to set data equal to it.
If we wanted to get access to the resolved value "I made it", we could have used the .then() method on data:
data.then(res => console.log(res))
This would've logged "I made it!"

Ref: https://bit.ly/3jFRBje

How do you separate a URL?

To help our algorithms understand separate mobile URLs, we recommend using the following annotations:.
On the desktop page, add a rel="alternate" tag pointing to the corresponding mobile URL. ... .
On the mobile page, add a rel="canonical" tag pointing to the corresponding desktop URL..

How do you split a URL in HTML?

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

How do you split a URL in node?

You can split the url string using the split() method by specifying a delimiter ( / in your case) and it will return an array.

What is the use of split function in JavaScript?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.