jeffreynolte
jeffreynolte

Reputation: 3779

Checking if src of img contains certain text with jQuery

I am looking to use jQuery contains to run through each image on a page and check if the src tag contains a certain http value. How would I run a check on the text in the src attribute with jQuery or javacript. I have the overview of what I am attempting below:

$('img').each(function(i){
  var img = $(this),
      imgSrc = img.attr('src'),
      siteURL = "http://url.com";

  if(!imgSrc.contains(siteURL)){
     imgSrc = siteURL + imgSrc;
  }
});                         

I have a feeling regex may be the way to go just don't know how for sure.

Upvotes: 2

Views: 18017

Answers (5)

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76880

i'd do (using indexOf):

$('img').each(function(i){
      var imgSrc = this.src;
      var siteURL = "http://url.com";

  if(imgSrc.indexOf(siteURL) === -1){
     imgSrc = siteURL + imgSrc;
  }
}); 

Upvotes: 6

ken
ken

Reputation: 3709

// find all img's without the siteURL, and add it
$('img:not([src^="http://url.com"])').each(function(i){
  this.src = siteURL + this.src;
}); 

Upvotes: 3

Tejs
Tejs

Reputation: 41246

Why not simply make a selector to do that?

 $('img[src*="http://url.com"]')

That should select just the elements with that text in the src tag, without you having to write custom logic.

Upvotes: 5

renil
renil

Reputation: 409

Please take a look at :contains() Selector.

http://api.jquery.com/contains-selector/

Upvotes: -1

Joseph Silber
Joseph Silber

Reputation: 219936

You'll want to search your imgSrc string if it has the siteURL string in it.

The indexOf method returns the position of the substring within the main string. If it's not found, it returns -1:

if (imgSrc.indexOf(siteURL) == -1) {
     imgSrc = siteURL + imgSrc;
}

Upvotes: 1

Related Questions