virsir
virsir

Reputation: 15509

How to match an image element with src by javascript regexp

I want to replace the img src by javascript regexp. The source html string may be not normalized, I mean it may be:

<img src="aa">
<img src="aa"/>
<img src="aa"></img>
< img SRC  =  " aa "></img >

How to make a javascript regular expression to cover all the conditions, and replace its src attribute.

Upvotes: 0

Views: 7772

Answers (4)

Dude2012
Dude2012

Reputation: 113

Why don't you just use "element.src.match"? here is an example:

<script>
function changeImage()
{
element=document.getElementById('myimage')
if (element.src.match("bulbon"))
  {
  element.src="pic_bulboff.gif";
  }
else
  {
  element.src="pic_bulbon.gif";
  }
}
</script>

<img id="myimage" onclick="changeImage()"
src="pic_bulboff.gif" width="100" height="180">

<p>Click the light bulb to turn on/off the light</p>

The whole example is at: http://www.w3schools.com/js/tryit.asp?filename=tryjs_lightbulb

Upvotes: 0

Ludovic Kuty
Ludovic Kuty

Reputation: 4954

You can make a case insensitive regex as shown here: Case insensitive regex in javascript

Then you have to take into account that there may be spaces anywhere :

<\s*img\s+src\s+=

And then you have a match. But your question does not specifiy what you are trying to replace and by what.

Upvotes: 0

RobG
RobG

Reputation: 147523

The value of an img element's src property can be accessed directly:

alert(someImg.src);

The value is a string, so you can operate on it using string methods. The surrounding markup is irrelevant, the innerHTML representing the element might be different in different browsers so you should not be using that.

If you want to use a regular expression to change the value, then operate on the related DOM property directly.

You do not state what you want to do with the value, but perhaps you want to replace some part of it with some other, then given the markup:

<img id="img0" src="image-red.jpg">

You can change it to "image-blue.jpg" using:

var img = document.getElementById('img0');
img.src = img.src.replace(/-red/,'-blue');

but you could also just assign the new value:

img.src = 'image-blue.jpg';

Upvotes: 1

Spycho
Spycho

Reputation: 7788

Use jQuery?

$('img').attr('src', '/my/new/source/value');

Upvotes: 1

Related Questions