How does Stack Overflow generate its SEO-friendly URLs?

后端 未结 21 1835
-上瘾入骨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:10

    I know it's very old question but since most of the browsers now support unicode urls I found a great solution in XRegex that converts everything except letters (in all languages to '-').

    That can be done in several programming languages.

    The pattern is \\p{^L}+ and then you just need to use it to replace all non letters to '-'.

    Working example in node.js with xregex module.

    var text = 'This ! can @ have # several $ letters % from different languages such as עברית or Español';
    
    var slugRegEx = XRegExp('((?!\\d)\\p{^L})+', 'g');
    
    var slug = XRegExp.replace(text, slugRegEx, '-').toLowerCase();
    
    console.log(slug) ==> "this-can-have-several-letters-from-different-languages-such-as-עברית-or-español"
    

提交回复
热议问题