How does Stack Overflow generate its SEO-friendly URLs?

后端 未结 21 2583
-上瘾入骨i
-上瘾入骨i 2020-11-22 04:27

What is a good complete regular expression or some other process that would take the title:

How do you change a title to be part of the URL like Stack

21条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 05:05

    You can also use this JavaScript function for in-form generation of the slug's (this one is based on/copied from Django):

    function makeSlug(urlString, filter) {
        // Changes, e.g., "Petty theft" to "petty_theft".
        // Remove all these words from the string before URLifying
    
        if(filter) {
            removelist = ["a", "an", "as", "at", "before", "but", "by", "for", "from",
            "is", "in", "into", "like", "of", "off", "on", "onto", "per",
            "since", "than", "the", "this", "that", "to", "up", "via", "het", "de", "een", "en",
            "with"];
        }
        else {
            removelist = [];
        }
        s = urlString;
        r = new RegExp('\\b(' + removelist.join('|') + ')\\b', 'gi');
        s = s.replace(r, '');
        s = s.replace(/[^-\w\s]/g, ''); // Remove unneeded characters
        s = s.replace(/^\s+|\s+$/g, ''); // Trim leading/trailing spaces
        s = s.replace(/[-\s]+/g, '-'); // Convert spaces to hyphens
        s = s.toLowerCase(); // Convert to lowercase
        return s; // Trim to first num_chars characters
    }
    

提交回复
热议问题