How to retrieve data-bind attribute value in html document

1

I had the need to obtain some values from the data attribute

I have the following:

<img data-bind="attr: {src: app.utils.getFavicon('http://gamovideo.com/9tbtyuoti8ae')}" src="http://www.google.com/s2/favicons?domain=gamovideo.com">

But I just need to get the part of the link

http://gamovideo.com/9tbtyuoti8ae

I have no idea how it could be, if you need more information about what you want to do, please indicate me in the comments.

Thanks in advance and Regards.

    
asked by andrio 12.04.2017 в 21:54
source

2 answers

1

You can do it with a regular expression:

const img = document.querySelector('img');
const bind = img.getAttribute('data-bind');
const regex = /(http|ftp|https):\/\/([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?/;

if (regex.test(bind)) {
  const url = regex.exec(bind)[0];
  console.info(url);
}
<img data-bind="attr: {src: app.utils.getFavicon('http://gamovideo.com/9tbtyuoti8ae')}" src="http://www.google.com/s2/favicons?domain=gamovideo.com"/>
    
answered by 12.04.2017 в 22:31
1

If regular expressions scare you, here is an example of how to make it simpler but equally functional;))

$(function (){
 url = $("img").data("bind").split("'")[1];
 console.log(url);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img data-bind="attr: {src: app.utils.getFavicon('http://gamovideo.com/9tbtyuoti8ae')}" src="http://www.google.com/s2/favicons?domain=gamovideo.com"/>

In the example I use jQuery because it's easy to use, cross-platform and lets you develop more by writing less.

Now I explain: the Method split divides a string of characters in an array using a character (or string) as a separator, in the case that you think it would be:

String to be converted:

attr: {src: app.utils.getFavicon('http://gamovideo.com/9tbtyuoti8ae')}" src="http:
//www.google.com/s2/favicons?domain=gamovideo.com

String (or Character) used as separate (or delimiter): '

Matrix created in the process of division:

0:attr: {src: app.utils.getFavicon(
1:http://gamovideo.com/9tbtyuoti8ae
2:)}" src="http://www.google.com/s2/favicons?domain=gamovideo.com

That's why when we execute: $("img").data("bind").split("'")[1] , it returns index 1 of the matrix which is in this case the url: 1:http://gamovideo.com/9tbtyuoti8ae .

I hope this serves you, Greetings !! ;))

    
answered by 12.04.2017 в 23:58