remove everything before the last occurrence of a character

前端 未结 5 1324
执念已碎
执念已碎 2020-12-13 23:34

I\'m trying to perform the following action on a string :

  • find the last occurrence of the character \"/\";
  • remove everything before that
5条回答
  •  Happy的楠姐
    2020-12-14 00:07

    Personally I'd use a regular expression:

    var result = string.replace(/^.*\/(.*)$/, "$1");
    

    If you're familiar with regular expressions (and you should be if not :-) then it's not as alien-looking as it is when they're unfamiliar.

    The leading ^ forces this regular expression to "anchor" the match at the start of the string. The \/ matches a single / character (the \ is to keep the / from confusing the regular expression parser). Then (.*)$ matches everything else from the / to the end of the string. The initial .* will swallow up as much as it can, including / characters before the last one. The replacement text, "$1", is a special form that means "the contents of the first matched group". This regex has a group, formed by the parentheses around the last .* (in (.*)$). That's going to be all the stuff after the last /, so the overall result is that the whole string is replaced by just that stuff. (If the pattern doesn't match because there aren't any / characters, nothing will happen.)

提交回复
热议问题