0

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.

  • I had to use regular expression to match it. Add it to the dom is not acceptable.
Ludovic Kuty
  • 4,868
  • 3
  • 28
  • 42
virsir
  • 15,159
  • 25
  • 75
  • 109

4 Answers4

1

Use jQuery?

$('img').attr('src', '/my/new/source/value');
Spycho
  • 7,698
  • 3
  • 34
  • 55
1

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';
RobG
  • 142,382
  • 31
  • 172
  • 209
0

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.

Community
  • 1
  • 1
Ludovic Kuty
  • 4,868
  • 3
  • 28
  • 42
0

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

Dude2012
  • 113
  • 1