Search code examples
javascriptregexpermalinks

Create a permalink with JavaScript


I have a textbox where a user puts a string like this:

"hello world! I think that __i__ am awesome (yes I am!)"

I need to create a correct URL like this:

hello-world-i-think-that-i-am-awesome-yes-i-am

How can it be done using regular expressions?

Also, is it possible to do it with Greek (for example)?

"Γεια σου κόσμε"

turns to

geia-sou-kosme

In other programming languages (Python/Ruby) I am using a translation array. Should I do the same here?


Solution

  • Try this:

    function doDashes(str) {
        var re = /[^a-z0-9]+/gi; // global and case insensitive matching of non-char/non-numeric
        var re2 = /^-*|-*$/g;     // get rid of any leading/trailing dashes
        str = str.replace(re, '-');  // perform the 1st regexp
        return str.replace(re2, '').toLowerCase(); // ..aaand the second + return lowercased result
    }
    console.log(doDashes("hello world! I think that __i__ am awesome (yes I am!)"));
    // => hello-world-I-think-that-i-am-awesome-yes-I-am
    

    As for the greek characters, yeah I can't think of anything else than some sort of lookup table used by another regexp.

    Edit, here's the oneliner version:
    Edit, added toLowerCase():
    Edit, embarrassing fix to the trailing regexp:

    function doDashes2(str) {
        return str.replace(/[^a-z0-9]+/gi, '-').replace(/^-*|-*$/g, '').toLowerCase();
    }