0

I am making a webpage so I can search google from a custom page. But when I click search it does search my input on google but the URL should be different when I input # and % and all these characters. So my question is how do I convert something like this :

http://www.google.com/#q=Hello World C#

to this :

http://www.google.com/#q=HEllo+world+C%23

using JavaScript

EDIT : This is the function I tried to use

    $('button#SubmitSearch').click
    (
        function()
        {
            window.location = encodeURIComponent("https://www.google.nl/#q=" + $('input#SearchBar').val());
        }
    );

and

    $('button#SubmitSearch').click
    (
        function()
        {
            window.location = "https://www.google.nl/#q=" + $('input#SearchBar').val();
        }
    );
Kara
  • 6,115
  • 16
  • 50
  • 57
  • You'll need to encode the search text. There's a handy Javascript function that does this, take a look at `encodeURIComponent` – Nick R Oct 30 '13 at 13:12

3 Answers3

1

Using encodeURI, eg :

console.log(encodeURI('http://www.google.com/#q=Hello World C#'));
> "http://www.google.com/#q=Hello%20World%20C#"

Or encodeURIComponent

console.log(encodeURIComponent('Hello World C#'));
> "Hello%20World%20C%23"

From your OP :

$('button#SubmitSearch').click(function(){
    window.location = "https://www.google.nl/#q=" + encodeURIComponent($('input#SearchBar').val());
});
OneOfOne
  • 95,033
  • 20
  • 184
  • 185
  • I wouldn't even have mentioned your *or* solution as it's kind of inferior in this context given that you would need to append the base URL. – CodingIntrigue Oct 30 '13 at 13:13
0

use the function encodeURIComponent:

encodeURIComponent('this is a string with special characters like # and ?')

hope it helps :)

David V
  • 185
  • 8
0

try this Var search = document.getElementById("searchbox"); Then use addeventlistener or onClick

key=key.replace(/ /g,"+"); document.location("http://google.com/#q" + search.value);