Catch the last occurrence in a javascript string

1

I have a string containing the following:

xx_xxxxx_0001_ABCDE_TESTE_INTRODUCAO_VIDEO

How would I always get the last word after the underline "_"?

The expected result would be:

VIDEO
    
asked by anonymous 13.07.2018 / 14:26

3 answers

12

Just use lastIndexOf that returns the position of the last occurrence of a string :

var texto = "xx_xxxxx_0001_ABCDE_TESTE_INTRODUCAO_VIDEO";
var ultima = texto.substring(texto.lastIndexOf("_")+1);
console.log(ultima);

For the scenario of the question it is very simple, but for other situations, indexOf or split as Leonardo Bosquett has shown may be alternatives.

    
13.07.2018 / 14:33
8

Just use split () and pick the last one position of the array using pop () :

let v = "xx_xxxxx_0001_ABCDE_TESTE_INTRODUCAO_VIDEO".split("_").pop();
console.log(v);

Notes:

  • Does not have code validations
  • Using split is best used if you use the other values of the array that is returned, if necessary is just the last word use lastIndexOf and substring as demonstrated in Ricardo Pontual's response.
13.07.2018 / 14:31
5

Just to give you one more chance, you can also do it with a simple regex. It does not mean that it is better than the already good alternatives shown, and will probably be less efficient as well.

The regex would be:

_([^_]*)$

Explanation:

_       - underline
([^_]*) - seguido de qualquer quantidade de carateres que não underline
$       - seguido de fim da linha

Example:

let texto = "xx_xxxxx_0001_ABCDE_TESTE_INTRODUCAO_VIDEO";
let ultimo = texto.match(/_([^_]*)$/)[1];

console.log(ultimo);

With match I get the content of first catch group, which is within ( and ) accessing the 1 position.

    
13.07.2018 / 15:45