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
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
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.
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:
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.