1

I am trying to split a string at the first occurence of "/" character. I'm able to split it into multiple elements using split('/') but when I try to split the the string at the 1st occurence of "/" character using a greedy operator (?) I'm not able to get the desired string..

Javascript Code

var url_string ="http://localhost:8080/myapp.html#/"
var sub_url = url_string.split(/(.+)?/)[1];

Current output.

http://localhost:8080/myapp.html#/

Desired Output..

myapp.html#/

Can't understand what I'm doing wrong.please help!!

Lucy
  • 1,812
  • 15
  • 55
  • 93

2 Answers2

3

You could use the power of Location and adjust the result.

var url_string = "http://localhost:8080/myapp.html#/"
var url = document.createElement('a');

url.href = url_string;
console.log(url.pathname.slice(1) + url.hash);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

You can use AngularJS $location.url() from the service $location:

// given URL http://localhost:8080/myapp.html#/
var url = $location.url();
// => "/myapp.html#/"

... and remove the first character.

Or you can the Web API URL:

var url = new URL('http://localhost:8080/myapp.html#/');
console.log(url.pathname.slice(1) + url.hash);
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46