0

I'm making an ajax call and I need any spaces to be replaced by plus signs (+). I'll show my code below, but currently I'm using .replace(), however, its only taking the first space and replacing it with a plus, but leaving all the rest. Any ideas?

    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);
});
David Schuler
  • 1,011
  • 2
  • 10
  • 21

2 Answers2

3

You just need to change this:

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

...to:

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

The g flag will tell replace to do a "global" replace instead of just replacing the first match.

Jacob
  • 77,566
  • 24
  • 149
  • 228
  • Thanks, that did it. I didn't realize it before, but all my strings had a space (now a +) at the end. I tried to fix this by adding .slice(0,-1) to the end of that statement, but no luck. Any ideas? – David Schuler Apr 27 '16 at 00:35
  • You could trim before doing the replace. Since older browsers don't have the trim method, I find this handy to replace leading/trailing spaces: `.replace(/^\s+|\s+$/g, '')` – Jacob Apr 27 '16 at 00:36
0

the problem is with the .replace regex you posted

try

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