0

I have this script from a google blog. Into for statement I want to add a part of code that replace space with "%20". My problem is that I can't imagine the syntax. Any idea? Thank you!

//<![CDATA[

    function showLabels(json){
        var label = json.feed.category;
        document.write('<div id="filters" class="portfolioSection">');
        document.write('<div>');
        document.write('<ul>');

        document.write('<li class="title">LABELS:</li>');
        document.write('<li><a class="current" href="#Blog1" data-filter="*">All</a></li>');
        document.write('<li><a class="no_labels" href="#Blog1" data-filter=".no-labels">no labels</a></li>');

        for (var i = 0; i < label.length; i++){
            document.write('<li><a href="#Blog1" data-filter=".' + label[i].term + '">' + label[i].term + '</a></li>');
        }

        document.write('<span class="show_ico icon-remove"/>');
        document.write('</ul>');
        document.write('</div>');
        document.write('</div>');
    }   

    document.write('<scr' + 'ipt src="' + HomePageUrl + '/feeds/posts/summary?max-results=0&alt=json-in-script&callback=showLabels"><\/scr' + 'ipt>');
//]]>

Edited: Spaces located in label[i].term into for statement. It contains label's name from a google blog. For example label can be Test Label. With space doesn't work when someone click on it cause url looks like this http://www.sitename.net/search/label/Test Label. What I want to do is to replace the space so it will look like this http://www.sitename.net/search/label/Test%20Label.

Simon
  • 71
  • 1
  • 8

3 Answers3

6

I literally just did this yesterday. If you want to replace spaces, the easiest way is:

var sentence = "This is a sentence"
sentence.split(" ").join("%20");
whatoncewaslost
  • 2,216
  • 2
  • 17
  • 25
6

Why not:

string.replace(/ /g, '%20')

Edited to fix.

JBux
  • 1,394
  • 8
  • 17
3
var str = "";
// label is the string you want to modify
for (var i = 0; i < label.length; i++) {
      if (label.charAt(i) == ' ') {
           str += "%20";
      } else {
           str += label.charAt(i);
      }
}
  • could anybody explain the downvotes? –  Jul 14 '15 at 21:07
  • I haven't down voted, but I imagine people would be because this seems a very slow way to go about the problem. It's not a wrong answer, just not the best one. – JBux Jul 14 '15 at 22:37
  • 1
    @JBux, he wanted to use a "`for` statement"... –  Jul 15 '15 at 05:57
  • 1
    I think he meant he wanted the solution to be inside the `for` statement inside his posted code. – JBux Jul 15 '15 at 06:56