2016-04-27 14 views
0
替換空格

我正在做一個ajax調用,並且需要用加號(+)替換任何空格。我將在下面顯示我的代碼,但是目前我正在使用.replace(),但是,它只會佔用第一個空間並用一個加號代替它,但剩下所有其他空間。有任何想法嗎?Ajax用+

function getImages() { 
    [].slice.call(arguments) 
    .map(function(artist) { 
     return artist.toString().replace(/\s+/, '+'); 
    }) 
    .forEach(function(artist) { 
     $.ajax({ 
     type: 'POST', 
     url: 'http://ws.audioscrobbler.com/2.0/', 
     data: 'method=artist.getinfo' + 
      '&artist=' + artist + 
      '&api_key=secret' + 
      '&format=json', 
     dataType: 'jsonp', 
     success: function(data) { 
      document.body.innerHTML += '<img src="' + data.artist.image[2]['#text'] + '" /><br>' 
     }, 
     error: function(code, message) { 
      alert('there was an error'+ message); 
     } 
     }); 
    }); 
} 
var values = [] 
$(document).ready(function() { 
    $('.artist').each(function() { 
    var self = $(this) 
    values.push(self.html()); 
    }); 

    getImages(values); 
}); 

回答

3

你只需要改變這一點:

return artist.toString().replace(/\s+/, '+'); 

...到:

return artist.toString().replace(/\s+/g, '+'); 

g標誌會告訴replace做一個 「全球性」 代替,而不是僅僅更換第一場比賽。

+0

謝謝,這做到了。我以前沒有意識到,但是我所有的琴絃末尾都有一個空格(現在是a +)。我試圖通過在該語句的末尾添加.slice(0,-1)來解決此問題,但沒有運氣。有任何想法嗎? –

+0

你可以在做替換之前修剪。由於舊版瀏覽器沒有修剪方法,我發現這個方法可以取代前導/尾隨空格: '.replace(/^\ s + | \ s + $/g,'')' – Jacob

0

問題是你貼

的.replace正則表達式嘗試

.replace(/\s+/g"+");