David Schuler David Schuler - 7 months ago 23
Javascript Question

Ajax replace spaces with +

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);
});

Answer

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.