Cut with Javascript a String indicating Strings as start and end

2

I have a string that contains code HTML with tags <img> in it, I need to create an array with the src of each img but I can not tell you by numbers where to cut, because I do not know where the tag appears img or where it ends

<p>Hola, esto es un ejemplo<img src="./img-uploads/345753e8-bba6-d75f-3f0f-0f4d0b9bd493.jpg" style="width: 757px;">&nbsp;más texto de prueba<img src="./img-uploads/48deeb1c-a32e-cc28-76b4-e59806c7b1d5.jpg" style="width: 50px;"><br></p>

My idea is to find as start <img src=" and as final, the next character in order that would be " , because what this code generates is an editor and the added style will always vary.

I solved it in a slightly weird way but it works to find in any string a piece using as index pieces of string that surround it

Thanks to Lois6b for your help , what I'm looking for right now is the correct answer, however, I leave the code in case someone wants to do something similar without being able to use getElementsByTagName.

var string = '<p>Hola, esto es un ejemplo<img src="./img-uploads/345753e8-bba6-d75f-3f0f-0f4d0b9bd493.jpg" style="width: 757px;">&nbsp;más texto de prueba<img src="./img-uploads/48deeb1c-a32e-cc28-76b4-e59806c7b1d5.jpg" style="width: 50px;"><br></p>'
var resultado = [];
var ultimo = -1;
do {
    var n = string.indexOf('<img src="',ultimo+1); // img
        ultimo=n;
    var m = string.indexOf('"',ultimo+10) // comillas

    if(n!=-1)
    resultado.push(string.slice(n+10, m));  //+10 por el tamaño de <img src= 
    ultimo=n;
} while (n!=-1);

console.log(resultado);
    
asked by Jean Rodríguez 19.01.2017 в 11:12
source

1 answer

2

For that you can use the getElementsByTagName("img"); function that returns a collection of elements , in this case whose Tag is img .

Iteras by the elements and for each one, you take the attribute src with .getAttribute("src"); so that you literally take out what contains that attribute. In your case, it would extract the relative URL without including the http://...

If you use .src to dry it would remove the full URL

var elementos= document.getElementsByTagName("img");
var imagenesSRC =  new Array (elementos.length);
for(var i=0;i<elementos.length;i++){
    console.log(elementos[i].getAttribute("src"));
    imagenesSRC[i] = elementos[i].getAttribute("src");
}
<p>Hola, esto es un ejemplo<img src="./img-uploads/345753e8-bba6-d75f-3f0f-0f4d0b9bd493.jpg" style="width: 757px;">&nbsp;más texto de prueba<img src="./img-uploads/48deeb1c-a32e-cc28-76b4-e59806c7b1d5.jpg" style="width: 50px;"><br></p>
    
answered by 19.01.2017 / 11:34
source