Ram Singh Ram Singh -5 years ago 100
Javascript Question

How to get Specific chars from string in jquery

I have following html, can't use "attr", so according to me only substring is the option to get specific data from following html:

<video poster="images/IMG_4979.jpg" controls=""><source type="video/mp4" src="video/IMG_4979.mp4"></source></video>

Actually, i want to get poster tag's data. i tried by following way, but it always return wrong data.

var pswp.currItem.html = '<video poster="images/IMG_4979.jpg" controls=""><source type="video/mp4" src="video/IMG_4979.mp4"></source></video>'
var misc = pswp.currItem.html.substring(0, pswp.currItem.html.indexOf('controls'));

i have created "pswp.currItem.html" as var here so that it could be easy to understand, but it is coming from this "pswp.currItem.html" object, on which attr is not working.

please help me how can i get poster tag's data. (image path)

Answer Source

You can cast the string to a JQuery object.

I have broken down the single steps for you for easy understanding.

// this is your HTML string
var html_str = '<video poster="images/IMG_4979.jpg" controls=""><source type="video/mp4" src="video/IMG_4979.mp4"></source></video>';

// now we create a JQuery object from your string
var $jq_obj = $(html_str);

// now we can access the JQuery object as if it were part of the DOM
var poster = $jq_obj.attr('poster');

// log the attribute
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download