views:

408

answers:

3

Hello,

i replace the submit url from the search form with this jquery snippet:

<script type="text/javascript">
$(document).ready(function() {
    $('.search-form').submit(function() {
        window.location.href = "/search-" + $('.search-form input:text').val() + "-" + "keyword"+ "-"+ "keyword2/" + $('.search-form input:text').val() + ".html";
     return false;
    });
});
</script>

work's fine and turns the url into a nice seo cleaned url.. but how can I replace the space, when someone types in "search me" the url looks like /search-search me-keyword-keyword2/search me.html with spaces.. but with + or - it would look much better.. I know str_replace from php, but no code for jquery.. thank you!!

+2  A: 

There's a native Javascript function called encodeURIComponent that's intended to do exactly what you need.

window.location.href = 
  "/search-" + 
  encodeURIComponent($('.search-form input:text').val()) + 
  "-" + "keyword" + "-" + "keyword2/" + 
  encodeURIComponent($('.search-form input:text').val()) + 
  ".html";
Pointy
A: 

http://www.w3schools.com/jsref/jsref_replace.asp

replace() method is native javascript. That'll get you what you want.

BenHayden
+1  A: 

Method 1: Using Replace

<script type="text/javascript">
$(document).ready(function() {
    $('.search-form').submit(function() {

        var value = $('.search-form input:text').val();
        value = value.replace(' ', ''); // replace

        window.location.href = "/search-" + value + "-" + "keyword"+ "-"+ "keyword2/" + value + ".html";
     return false;
    });
});
</script>

Method 2: Encoding URL

<script type="text/javascript">
$(document).ready(function() {
    $('.search-form').submit(function() {

        // encode url
        var value = encodeURIComponent($('.search-form input:text').val());

        window.location.href = "/search-" + value + "-" + "keyword"+ "-"+ "keyword2/" + value + ".html";
     return false;
    });
});
</script>

Note that replace method would work even in JQuery because Jquery is simply library of javascript :)

Sarfraz
thank you, works great!!!
elmas
@elmas: You are welcome :)
Sarfraz