2016-11-30 117 views
1

最後一次出現,我有以下字符串:「\ IonSubsystem1 \ TRAN-88311」刪除字符串

我要拉斷的最後一個字:TRAN-88311是一個ID,在一個通用的方法。

我該怎麼辦呢?

我曾想過,也許發現的「\」信中最後一次出現,但在我看來,我不能運行JS順序如下:

var a = "\\IonSubsystem1\TRAN-88311"; 
a.lastIndexOf('\') ==> error in here. 

任何其他解決辦法是值得歡迎的,謝謝提前

+0

你是如何想的子串的邊界以去除定義? – Richard

+0

讓評論反斜槓非常困難。 – Pointy

回答

4

這很容易。

var a = "\\IonSubsystem1\\TRAN-88311"; 
 
a = a.split("\\"); 
 
console.log(a[a.length-1]);

在你的字符串表示時,\T被轉換爲製表符。

+0

如果split \ in string'「\\」' – Mahi

+0

@Mahi你怎麼辦?那是不可能的。 –

1

這應做到:

var a = "\\IonSubsystem1\\TRAN-88311";var b = a.split('\\');console.log(b[b.length-1]); 
0

當然,你必須轉義反斜線,否則頂點將被替代逃脫(引發錯誤)

錯誤

x.indexOf('\'); //The first apex opens the string, the slash will prevent the second apex to close it 

正確

x.indexOf('\\'); //The first apex open the string, the first backslash will escape the second one, and the second apex will correctly close the string 
+0

同時檢查答案中的字符串的顏色,您可以很容易地看到錯誤的引起註釋顯示爲文本(因爲字符串從未關閉),而在正確的一箇中,一切按預期行事 –

1

在這裏使用Regex捕獲組是一個解決方案。

var a = '\\IonSubsystem1\\TRAN-88311'; 
 
var id = a.replace(/(\\.*\\)(.*)/g, '$2'); 
 

 
alert(id);