2016-11-25 92 views
1

我想在第一次出现“/”字符时分割字符串。我可以使用split('/')将它拆分为多个元素,但是当我尝试使用贪婪操作符(?)在第一次出现“/”字符时分割字符串时,我无法获得所需的字符串..仅在第一次出现指定字符时分割字符串

JavaScript代码

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

电流输出。

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

所需的输出..

myapp.html#/ 

不能明白我在做什么wrong.please帮助!

+0

你为什么不更换的 “http://本地主机:8080 /” 空,并宣布与该值的变量;即:var SERVER_URL =“http:// localhost:8080 /”; var sub_url = url_string.replace(SERVER_URL,“”) –

+0

或'.split(/ \ /(?= [^ \ /] * \/$)/)[1]' –

+0

或['/ [^ \ /] * \/$ /'](https://regex101.com/r/Ls40Yx/1) –

回答

3

您可以使用Location的功率并调整结果。

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);

+0

OP请求:'myapp.html#/' –

1

您可以使用AngularJS $location.url()从服务$location

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

...并删除第一个字符。

或者你可以在Web API URL

var url = new URL('http://localhost:8080/myapp.html#/'); 
 
console.log(url.pathname.slice(1) + url.hash);

相关问题