简体   繁体   中英

Is it possible to extract image from text with jQuery or JavaScript?

Good day, I'm trying to make an article content with ckeditor . Here is an example from my input.

<p>I have two images&nbsp;<img alt="" src="http://localhost:84/lf//assets/images/commingsoon.png" style="height:225px; width:225px" />&nbsp;and this&nbsp;&nbsp;<img alt="" src="http://localhost:84/lf//assets/images/article2.jpg" style="height:91px; width:122px" /></p>  

As you can see there are two images, and i want to the first image as my thumbnail. for now, i just want to extract it .

The result from extract is something like this

http://localhost:84/lf//assets/images/commingsoon.png

var myString = '<p>I have two images&nbsp;<img alt="" src="http://localhost:84/lf//assets/images/commingsoon.png" style="height:225px; width:225px" />&nbsp;and this&nbsp;&nbsp;<img alt="" src="http://localhost:84/lf//assets/images/article2.jpg" style="height:91px; width:122px" /></p>';
var result = (someprosess)

You can use find() , first() and attr() to access the URL of the first image from your string.

 var myString = '<p>I have two images&nbsp;<img alt="" src="http://localhost:84/lf//assets/images/commingsoon.png" style="height:225px; width:225px" />&nbsp;and this&nbsp;&nbsp;<img alt="" src="http://localhost:84/lf//assets/images/article2.jpg" style="height:91px; width:122px" /></p>'; var result = $(myString).find('img').first().attr('src'); console.log(result);
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

You can use either JavaScript or jQuery to search for the first instance of an image and parse out its src

As an example, using jQuery (if there is always going to be an image in the content)

var imgPointer = $('body').find('img');
var imgSrc = imgPointer[0].attr('src');

Here you go with a solution using jQuery

 console.log($('p').find('img:first').attr('src'));
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p>I have two images&nbsp;<img alt="" src="http://localhost:84/lf//assets/images/commingsoon.png" style="height:225px; width:225px" />&nbsp;and this&nbsp;&nbsp;<img alt="" src="http://localhost:84/lf//assets/images/article2.jpg" style="height:91px; width:122px" /></p>

Hope this will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM