0

I have regular expression for extracting the source of images in html string coming from json api in react native app, that works fine. The output is in urls array:

var m,
urls = [],
str = '<img class="d-block mx-auto" src="http://www.website.com/wp-content/uploads/2020/05/66189-759x493.jpg" />,
rex = /<img[^>]+src="?([^"\s]+)"?\s*\alt="First slide">/g;
      while ( m = rex.exec( str ) ) {
          urls.push( m[1] );
      }
console.log(urls);  // ["http://www.website.com/wp-content/uploads/2020/05/66189-759x493.jpg",...]

However I want rex that gets only the source of images inside class carousel-item :

str = '<div class="carousel-item"> <img class="d-block mx-auto" src="http://www.website.com/wp-content/uploads/2020/05/66189-759x493.jpg" />';
Tarif Aljnidi
  • 288
  • 7
  • 16

1 Answers1

0

If you're not married to using RegEx, you can write the HTML string to an actual dom node, and then manipulate it that way. For each string:

var imgNodes = []
var str = '<img class="d-block mx-auto" src="http://www.website.com/wp-content/uploads/2020/05/66189-759x493.jpg" />

var wrapper= document.createElement('div');
wrapper.innerHTML= str
var strAsDOMNode = wrapper.firstChild;
ingNodes.push(strAsDOMNode)

Then you can filter the ones that have 'carousel-item' in their classList:

const sources = imgNodes
  .filter( node => node.classList.contains('carousel-item') === true )
  .map( node => node.src )

I know this doesn't use RegEx but it does accomplish your goal.

Seth Lutske
  • 9,154
  • 5
  • 29
  • 78