Tom
Tom

Reputation: 275

Trouble With .replace() - Only Works With First Matched Character?

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?

Upvotes: 2

Views: 3523

Answers (3)

Robusto
Robusto

Reputation: 31883

String.replace() only does one replacement if the first argument is a string literal. Use a Regex as your first argument instead. Example:

$(this).attr('src','/images/'+$(this).attr('alt').replace(/ /g,'-')+'.png');

or

$(this).attr('src','/images/'+$(this).attr('alt').replace(/\s/g,'-')+'.png');

Upvotes: 3

Nick Craver
Nick Craver

Reputation: 630569

Use /g here, like this:

$('div.copy').find('img').each(function() {
    $(this).attr('src','/images/'+$(this).attr('alt').replace(' '/g,'-')+'.png');
});
//or the regex version:
$('div.copy').find('img').each(function() {
    $(this).attr('src','/images/'+$(this).attr('alt').replace(/ /g,'-')+'.png');
});

/g is 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.

Upvotes: 5

John Strickler
John Strickler

Reputation: 25421

Should do the trick.

$(this).attr('src','/images/'+$(this).attr('alt').replace(/\s/g,'-')+'.png');

Upvotes: 2

Related Questions