Categories
JavaScript Answers

How to extract image src from a string easily with JavaScript?

Spread the love

Sometimes, we want to extract image src from a string easily with JavaScript.

In this article, we’ll look at how to extract image src from a string easily with JavaScript.

How to extract image src from a string easily with JavaScript?

To extract image src from a string easily with JavaScript, we can create a div, set the innerHTML property of the div to the img element string.

And then we can select the img element from the div and get the src property from it.

For instance, we write:

const imgStr = '<img src="http://example.com/img.jpg">'

const getImgSrc = (imgStr) => {
  const div = document.createElement('div')
  div.innerHTML = imgStr
  const img = div.querySelector('img')
  return img.src
}

console.log(getImgSrc(imgStr))

to define the getImgSrc property to a function that takes the imgStr string.

In it, we create a div with createElement.

Then we set div.innerHTML to imgStr.

And then we call div.querySelector with 'img' to get the img element.

Finally, we return the img.src property.

As a result, the console log logs 'http://example.com/img.jpg'.

Conclusion

To extract image src from a string easily with JavaScript, we can create a div, set the innerHTML property of the div to the img element string.

And then we can select the img element from the div and get the src property from it.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *