开发者

Urlify user input in real time

I'd like to basically have a Title field and a Title for URL field.

So bas开发者_开发技巧ically the user inputs a movie name: "From Paris With Love" and it would be in the field below as "from-paris-with-love".

However I was wondering if there's something similar already out there and knew someone here would know! ;)

  • Aaron

EDIT:

http://www.thewebsitetailor.com/jquery-slug-plugin/ is perfect!


You can use the JavaScript function encodeURIComponent, which will replace spaces and any other characters that can't be used in URLs.

Reference: https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference:Global_Functions:encodeURIComponent


I do something exactly like this in my own application. There is some server side code to it as well which is used to validate the generated value, but I have created a JavaScript helper to do a client-side "Urlify". It will replace ' ', ':', '\', and '/' with a '-', then remove all non-alpha-numeric characters, and finally clean up any instances of more than one '-' side-by-side.

function FormatForUrl(str) {
    return str.replace(/_/g, '-')
        .replace(/ /g, '-')
        .replace(/:/g, '-')
        .replace(/\\/g, '-')
        .replace(/\//g, '-')
        .replace(/[^a-zA-Z0-9\-]+/g, '')
        .replace(/-{2,}/g, '-')
        .toLowerCase();
};

Examples

  • "Hello World" - "hello-world"
  • "The car cost $1700" - "the-car-cost-1700"
  • "Hey, let's go to the corner-store." - "hey-lets-go-to-the-corner-store"
  • "www.mywebsite.com/page1.html" - "wwwmywebsitecom-page1html"
  • "email@mywebsite.com" - "emailmywebsitecom"


A very simple approach would be to remove all non alpha-numeric chars with dashes:

$(":input").bind("keyup", function(){
  $(".seo").text( $(this).val().replace(/[^a-z0-9]+/gi, "-") ); 
});

Converting Jonathan says hello, world to jonathan-says-hello-world.

Demo Online: http://jsbin.com/eqama/2/edit


there a good urlify library used by the Django Project. I think the license is BSD or MIT. You'll need to check. You can find it here: http://code.djangoproject.com/browser/django/trunk/django/contrib/admin/media/js/urlify.js

That script will remove unecessary characters replace spaces with dashes and will replace accent and other special character with others.

The way i use it with jquery i check when the title text box has lost focus and update my url


//Note i have modify that URLify method to accept one argument instead of 2, don't need length
 $(document).ready(function() {
            $('#Title').focusout(function() {
                $('#Permalink').val(URLify($(this).val()));                
            });
        });


This is the one I use.

$.fn.slug = function(){
    return this
            .val()
            .replace(/[^a-zA-Z 0-9-]+/g,'')
            .toLowerCase()
            .replace(/s/g,'-')
};
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜