David Schuler David Schuler - 2 years ago 96
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() {
.map(function(artist) {
return artist.toString().replace(/\s+/, '+');
.forEach(function(artist) {
type: 'POST',
url: 'http://ws.audioscrobbler.com/2.0/',
data: 'method=artist.getinfo' +
'&artist=' + artist +
'&api_key=secret' +
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)


Answer Source

You just need to change this:

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


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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download