-3

I was wondering is it possible to replace the %20 to a + whenever I click the button to add the textbox value to the url.

$(function () {
    $('#btn').click(function() {
        var url = "www.urlname.com/results.html?value=";
        url += $('#textbox').val();
        window.location = url;
    });
});

Thanks

Derg
  • 3
  • 4

4 Answers4

2

Yep with a regex for all occurrences $('#textbox').val().replace(/%20/g, '+');

Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
  • Did it? I can't get the replace function to recognize the encoded space as a space in the string. – hofo Feb 26 '15 at 16:36
2

I haven't tested it but this should work. You want to replace the spaces in the value. They're not encoded to the entity at this point.

$(function () {
    $('#btn').click(function() {
        var url = "www.urlname.com/results.html?value=";
        var textboxValue = $('#textbox').val();
        textboxValue = textboxValue.replace(/ /g, "+");
        url += textboxValue;
        window.location = url;
    });
});
hofo
  • 522
  • 1
  • 4
  • 16
0

Have you tried this?

$(function () {
    $('#btn').click(function() {
        var url = "www.urlname.com/results.html?value=";
        url += $('#textbox').val();
        window.location = url.replace(new RegExp(' ','g'),'+');
    });
});
Trey
  • 5,480
  • 4
  • 23
  • 30
  • Additionally the textbox string won't have the spaces encoded yet. – hofo Feb 26 '15 at 16:28
  • Right you are, the anwser has been updated to replace all matches, and handle spaces instead of html entities – Trey Feb 26 '15 at 16:29
0

When you're creating URL parameters dynamically, you shouldn't use ad hoc substitutions to encode them. Javascript provides the encodeURIComponent function to perform all required encodings. So you should write:

url += encodeURIComponent($('#textbox').val());
Barmar
  • 741,623
  • 53
  • 500
  • 612