I’m trying to add a function in my jQuery script that constructs a complete src path for an img based on its alt attribute. The idea is to make the code as slim as possible so that the non-techies who handle it don’t break anything; all they’d have to do is get the alt attribute correct and the rest of the path is constructed automagically by the script.
Anyway, my file names include hyphens, and to make it extra foolproof I want to allow spaces in the alt attribute that would be replaced with hyphens in the src attribute. The trouble is, the .replace() command only seems to work on the first matched character, so if I have three words in the alt attribute to describe the img, the second space doesn’t get replaced and the img path breaks.
Here’s the code in question:
<div class="copy"><img alt="three word alt" /></div>
<script>
$('div.copy').find('img').each(function() {
$(this).attr('src','/images/'+$(this).attr('alt').replace(' ','-')+'.png');
});
</script>
The end result should be
<img src="/images/three-word-alt.png" alt="three word alt" />
But instead it comes out like this:
<img src="/images/three-word alt.png" alt="three word alt" />
Is there maybe a better way of doing this?
Use
/ghere, like this:/gis the global modifier to match all occurrences instead of just the first (the default)…JavaScript’s a bit odd in it’s behavior in that respect, compared to most other languages.