How to retrieve data-bind attribute value in html document


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

I have the following:

<img data-bind="attr: {src: app.utils.getFavicon('')}" src="">

But I just need to get the part of the link

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

2 answers


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.,@?^=%&:/~+#-]*[\[email protected]?^=%&/~+#-])?/;

if (regex.test(bind)) {
  const url = regex.exec(bind)[0];;
<img data-bind="attr: {src: app.utils.getFavicon('')}" src=""/>
answered by 12.04.2017 в 22:31

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];
<script src=""></script>
<img data-bind="attr: {src: app.utils.getFavicon('')}" src=""/>

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('')}" src="http:

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

Matrix created in the process of division:

0:attr: {src: app.utils.getFavicon(
2:)}" src="

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: .

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

answered by 12.04.2017 в 23:58