开发者

Javascript Replacing Spaces within an Array

I'm ok at 开发者_StackOverflowPHP, 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('');


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.


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


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('');


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜