Several urls arrive in an array from which I want to extract the last part
http://130.10.1:8087/tests/downloadFile/file.txt
so far I have only managed to get what goes before the file name, but what I want is to only get the name of said files file.txt
var url = "http://130.10.1:8087/pruebas/downloadFile/archivo.txt";
var ultimaPosicion = url.lastIndexOf('/');
var nivelAnterior = url.substr(0, ultimaPosicion);
console.log(nivelAnterior);
I'm new to JS, can you help me please?
With the .split() method you can save a string in an array, dividing it according to the char you send as a parameter, if you send a '/' as a parameter it will split the string using / as a reference, we do a split to the string, and we take the last value of the array, which will return the value you are looking for
This may also work for you:
where what we do is, through the slice() method we extract the piece of string that starts at the position obtained with lastIndexOf() until the end, and we add +1 to it to avoid the bar
/
You could use
split("/")
to separate the string at each/
it finds. After this you should go to the last position of the array as follows:Your code would be like this: