views:

50

answers:

4

This is the function I am working with:

function replaceH1s() {
  $("h1").each(function(){
    h1name = $(this).text();
    stuff = h1name.toLowerCase().replace(' ','-');
    $(this).html('<img src="/assets/image/h1_' + stuff + '.png" alt="' + h1name + '" />');
  })
}

I can't figure out for the life of me why this function replaces the first space in h1name string with a hyphen, but not any of the subsequent ones. I tried unescaping and escaping (and then replacing %20 it stumbles upon with hyphens, but that did the same thing). I tried regular expressions for catchall whitespace and that did the same thing. I feel like I am not seeing something super fundamental here.

A: 

The replace function was designed to only replace the first instance of the string you are searching for. If you want to replace all instances, then using regular expressions would work better.

take a look at this page for more information.

Gabriel McAdams
+4  A: 

You need to specify a global regular expression. Otherwise it only matches the first occurrence.

// regular expression
    function replaceH1s() {
      $("h1").each(function(){
        h1name = $(this).text();
        stuff = h1name.toLowerCase().replace(/\s+/g, '-');  // matches all whitespace
                                                           // use / /g to match a single space
        $(this).html('<img src="/assets/image/h1_' + stuff + '.png" alt="' + h1name + '" />');
      })
    }

// firefox only
    function replaceH1s() {
      $("h1").each(function(){
        h1name = $(this).text();
        stuff = h1name.toLowerCase().replace(' ', '-', 'g');
        $(this).html('<img src="/assets/image/h1_' + stuff + '.png" alt="' + h1name + '" />');
      })
    }
C-Mo
A: 

If you were trying to replace all spaces with - your close but not quite there

The replace function in JavaScript only replaces the first value it finds that matches and quits. Here is a replaceAll function.

stuff = h1name.toLowerCase().replace(' ' + /g, '-');​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
alert(stuff); //make sure this is what you want

the /g specifies replace all.

Aardvark
`' '` divided by `g`??
Roatin Marth
God help you if g is zero.
treeface
Hey, thanks guys this worked. I could swear I had tried /\s/g in that spot, and it wasn't working... then I noticed that the image I was trying to insert there was accidentally in the wrong folder and that is why I didn't register the regex as working at first. Amateur hour. :/
Hoatzin
+1  A: 
stuff = h1name.toLowerCase().replace(/ /g, '-');
Ned Batchelder