开发者

issue with replace() method in javascript when replacing spaces

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 a开发者_StackOverflow社区ny 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.


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 + '" />');
      })
    }


stuff = h1name.toLowerCase().replace(/ /g, '-');


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜