获取第一次出现'x'从反面看

get characters up to first occurrence of 'x' from reverse

本文关键字:获取 第一次      更新时间:2023-09-26

我想从右到左将字符串拆分为第一个出现"dot"的字符串。

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

您可以通过DOT split,并使用pop()来获得结果数组的最后一个元素:

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

最简单、最有效的方法是用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)); 

您可以拆分并弹出

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

或者你可以将它与一堆不同的reg exp:进行匹配

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