2016-11-25 42 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);

相關問題