2017-10-10 44 views
-4

說我有一個字符串:var str="localhost:20012/prj/duck/duck/woohoo"替換所有在JavaScript中相同的單詞?

正如您可能已經注意到在上述字符串處有2 /duck。供參考:可能還有更多。

我基本上想要的是刪除所有與見好就收要那麼它會是這樣的:localhost:20012/prj/duck/woohoo

+0

https://stackoverflow.com/questions/16843991/remove-occurrences-of-duplicate-words-in-a-string –

+0

@Whatever,它是爲你工作? –

回答

0

您可以使用split方法,然後就通過傳遞的回調提供的函數刪除使用filter方法重複。

var str="localhost:20012/prj/duck/duck/woohoo"; 
 
str=str.split('/').filter(function(item,index,str){ 
 
    return str.indexOf(item)==index; 
 
}).join('/'); 
 
console.log(str);

相關問題