开发者

How would I remove from spaces from a search form using jQuery?

开发者 https://www.devze.com 2022-12-21 16:37 出处:网络
I\'ve replaced the submit URL from the search form with this jQuery snip开发者_开发百科pet: <script type=\"text/javascript\">

I've replaced the submit URL from the search form with this jQuery snip开发者_开发百科pet:

<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>

This works fine and turns the URL into a nice SEO cleaned URL. But how can I replace the spaces?

When someone types in "search me" the URL looks like /search-search me-keyword-keyword2/search me.html with spaces. With + or - it would look much better. I know of str_replace from PHP, but how would I go about this in jQuery?


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";


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 :)


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

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


You could remove spaces with using mod_rewrite. It’s quite useful way. You can also remove spaces from URLs by replacing spaces by %20, but that only helps with spaces and won't escape other characters. What you really need to do is use a URL-escaping function.

0

精彩评论

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

关注公众号