2016-01-07 15 views
-1

我想從右到左匹配將字符串分割爲第一個出現的'點'。從反向獲得字符到第一個出現'x'

//if i have the input string as follows 
 

 
    var string = "hi.how.you" ; 
 
//i need the output as following 
 

 
    output="you";

+0

斯普利特'。 '並得到最後一個元素。爲什麼使用正則表達式? –

回答

2

可以split通過DOT和使用pop()得到結果數組的最後一個元素:

var string = "hi.how.you" ; 
var last = string.split('.').pop() 
//=> you 
0

您可以分裂和彈出

"hi.how.you".split(".").pop() 

或者你可以匹配我噸,一羣不同的REG EXP的:

"hi.how.you".match(/\.([^\.]+)$/)[1] 
0

最簡單,最有效的辦法就是找到最後.lastIndexOfsubstring

var s = "hi.how.you"; 
 
s = s.substring(s.lastIndexOf(".") + 1); 
 
// It will return the part after the last `.` 
 
console.log(s); 
 
// It will return the input string if `.` is missing 
 
console.log("hihowyou".substring("hihowyou".lastIndexOf(".") + 1));

相關問題