Separate a url with Javascript and save it in a variable

1

I would like to save the url in a variable, the url comes in this way

https://www.midominio.com/sites/document/indice1.txt

I just need https://www.midominio.com/sites/document/

thanks.

    
asked by elsa 04.10.2016 в 21:26
source

3 answers

3

You need to review the JavaScript Bible, String.prototype.substring() (< em> Mozilla ) :

Here is an example:

var cadenaDeTexto = "https://www.midominio.com/sites/document/indice1.txt";
var ultimoSlash = cadenaDeTexto.lastIndexOf("/"); 
console.log(ultimoSlash);
console.log(cadenaDeTexto.substring(0, ultimoSlash+1));

var hastaSites = cadenaDeTexto.indexOf('/document');
console.log(hastaSites);
console.log(cadenaDeTexto.substring(0, hastaSites+1));
    
answered by 04.10.2016 / 21:28
source
1

I could use Replace to replace in the array (what returns Split ) by applying the Pop that simulates a Desapilar (Remove the last element stacked in this case index1.txt) (Stack ) For more information on these methods go to the documentation (The First) link

    var str = "https://www.midominio.com/sites/document/indice1.txt";
    var result = str.replace(str.split('/').pop(),'');
    console.log(result);
    
answered by 04.10.2016 в 21:44
0

Use a regular expression like the following:

/(^.+\/).+\..{3}$/
  • () capture group
  • ^ start of the expression
  • . any character
  • + At least one or more characters
  • \/ The diagonal is a special character so you have to escape it
  • \. The point is a special character so you have to escape it
  • {3} Three characters equal to the predecessor
  • $ end of expression

Example:

var URL = "https://www.midominio.com/sites/document/indice1.txt";
var re =/(^.+\/).+\..{3}$/
var resultado = re.exec(URL);
console.log(resultado[1]);
    
answered by 13.02.2017 в 21:04