2010-06-12 44 views
1

你好在這裏掙扎的人..Javascript替換

是否有可能在第一個正斜槓之間用「」替換任何東西,但保留其餘部分?

例如變種會

string "/anything-here-this-needs-to-be-replaced123/but-keep-this"; 

最終會像這樣

string "/but-keep-this"; 

。希望取得SENCE

回答

4

你可以簡單地使用`lastIndexOf`就一定要得到的只是最後一個斜線/

var str = "/anything-here-this-needs-to-be-replaced123/but-keep-this"; 
var myarray = str.split('/'); 
alert('/' . myarray[2]); 
+0

這沒有OP預期的輸出'「/ but-keep-this」',儘量不要使用'.split()'爲'.substring()'做了什麼:) :) – 2010-06-12 12:21:26

+1

@Nick Craver:它確實:http://jsbin.com/ifabe3。你說得對'substring'可能是一條路。 OP可能會考慮那些有這個答案的人,如果這不能解決他正在做的事情。 – Sarfraz 2010-06-12 12:25:00

+0

@Sarfraz - '「/ but-keep-this」!=「but-keep-this」'',我的觀點是你缺少斜線:) – 2010-06-12 12:27:15

2

像這樣:

var string = "/anything-here-this-needs-to-be-replaced123/but-keep-this"; 
string = string.substring(string.indexOf('/', 1)); 

You can view a demo here to play with,該.indexOf() method帶有一個可選的第二個參數,說從哪裏開始搜索,只需使用即可在這裏。

如果你想刪除所有斜線開頭(從例子不清楚),改變它有點.lastIndexOf()沒有開始的說法,這樣的:

var string = "/anything-here-this-needs-to-be-replaced123/but-keep-this"; 
string = string.substring(string.lastIndexOf('/')); 

You can play with that here,效果是一樣的例如,但在更多斜槓的情況下會有所不同。

+0

更好的分流(我假設他解析道) – nico 2010-06-12 12:02:40

+0

@nico - 我不知道關於這個(模棱兩可的例子)...我重新閱讀了這個問題,並且在你評論時已經添加了它:) – 2010-06-12 12:04:37

3
var s = "/anything-here-this-needs-to-be-replaced123/but-keep-this"; 

pos = s.lastIndexOf("/"); 

var s2 = s.substring(pos); 

alert(s2);