Justin
Justin

Reputation: 3

Javascript Replacing Spaces within an Array

I'm ok at PHP, but no nothing about Javascript, so I have no idea how to proceed here. I'm trying to replace spaces with a "+" in line 3. Anybody know why it's not working? Thanks!

var tn_dv_suggestions = new Array();
for(var tn_counter=0; tn_counter < tn_top_performers.length; tn_counter++)
tn_top_performers[tn_counter]=tn_top_performers[tn_counter].replace(" ","+");
tn_dv_suggestions.push("<a style='font-family: Verdana, Arial; font-size: 14px;' target='_blank' href='http://www.<?=$siterow['Domain']?>/Buy-"+escape(tn_top_performers[tn_counter]) +"-<?=urlencode($siterow['CitySearchName'])?>-Tickets' >"+tn_top_performers[tn_counter] +"</a><br />");
document.getElementById('tn_dv_suggestions089hZ').innerHTML=tn_dv_suggestions.join('');

Upvotes: 0

Views: 4269

Answers (4)

Oliver Moran
Oliver Moran

Reputation: 5167

Your use of String.replace() is fine. The problem is that you are missing curly brackets surrounding all of the statements you want in the loop.

Fixed code:

var tn_dv_suggestions = new Array();
for (var tn_counter=0; tn_counter < tn_top_performers.length; tn_counter++) {
  tn_top_performers[tn_counter]=tn_top_performers[tn_counter].replace(" ","+");
  tn_dv_suggestions.push("<a style='font-family: Verdana, Arial; font-size: 14px;' target='_blank' href='http://www.<?=$siterow['Domain']?>/Buy-"+escape(tn_top_performers[tn_counter]) +"-<?=urlencode($siterow['CitySearchName'])?>-Tickets' >"+tn_top_performers[tn_counter] +"</a><br />");
}
document.getElementById('tn_dv_suggestions089hZ').innerHTML=tn_dv_suggestions.join('');

Upvotes: 0

lucian.pantelimon
lucian.pantelimon

Reputation: 3669

Tested on FF3 and Chrome.

tn_top_performers[tn_counter]=tn_top_performers[tn_counter].replace(/ /g,"+");

Edit: Don't forget the " "(space) between the forward slashes.

Upvotes: 0

Mike Lewis
Mike Lewis

Reputation: 64147

Here is a solution using array.map:

var replaceInArray = function(str){
  return str.replace(/\s+/g, "+")
}

var arr = ["Summer is Great", "Winter is terrible"]

arr.map(replaceInArray);
// returns => ["Summer+is+Great", "Winter+is+terrible"]

Your problem was that you were only replacing the first instance of " ". To fix this, use the global flag, by using g with your regex.

Upvotes: 3

wildcard
wildcard

Reputation: 7503

you probably replace only first space found. to replace all of them, you'll need global flag. try .replace(/\ /g, "+");

Upvotes: 1

Related Questions