J
J
jsonuser2021-01-25 06:26:51
HTML
jsonuser, 2021-01-25 06:26:51

How to get src value from img?

For example, there is a line "< im g src="link">1234566 4553342 aaa"

I need to extract the src value from img, how can I do it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander, 2021-01-25
@jsonuser

const strings = [
  '<img src="link">1234566 4553342 aaa',
  '<div><img class="super-img" src="https://example.com"/></div>',
  'src="1"',
  '<img src=\'../img.png\'/>'
];
const expression = /img.+?src=(["'])(.+)\1/;

for (const string of strings) {
  const src = (string.match(expression) || [])[2] ?? null;
  console.log(string);
  console.log(src);
}
/*
<img src="link">1234566 4553342 aaa
link

<div><img class="super-img" src="https://example.com"/></div>
https://example.com

src="1"
null

<img src='../img.png'/>
../img.png
*/

A
approximate solution, 2021-01-25
@approximate_solution

const str =  '<img src="link">1234566 4553342 aaa>';

const img = document.createElement('img');
img.innerHTML = str;

console.log(img) -----/ here is your img tag
and then get the src attribute with getAttribute('src');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question