我在CodeIgniter的一个应用程序上工作,我试图使表单上的字段动态生成URL段塞。我想做的是删除标点符号,将其转换为小写字母,并将空格替换为连字符。比如,Shane's Rib Shack会变成shanes-rib-shack。

这是我目前所掌握的。小写部分很容易,但替换似乎根本不起作用,我也不知道要删除标点符号:

$("#Restaurant_Name").keyup(function() {
  var Text = $(this).val();
  Text = Text.toLowerCase();
  Text = Text.replace('/\s/g','-');
  $("#Restaurant_Slug").val(Text);  
});

当前回答

希望这能挽救某人的一天…

/* Encode string to slug */ function convertToSlug( str ) { //replace all special characters | symbols with a space str = str.replace(/[`~!@#$%^&*()_\-+=\[\]{};:'"\\|\/,.<>?\s]/g, ' ') .toLowerCase(); // trim spaces at start and end of string str = str.replace(/^\s+|\s+$/gm,''); // replace space with dash/hyphen str = str.replace(/\s+/g, '-'); document.getElementById("slug-text").innerHTML = str; //return str; } <input type="text" onload="convertToSlug(this.value)" onkeyup="convertToSlug(this.value)" value="Try it Yourself" /> <p id="slug-text"></p>

其他回答

更强大的纯JavaScript段代码生成方法。它基本上支持所有西里尔字母和许多变音字母(德语、丹麦语、法语、土耳其语、乌克兰语等)的音译,但可以轻松扩展。

function makeSlug(str) { var from="а б в г д е ё ж з и й к л м н о п р с т у ф х ц ч ш щ ъ ы ь э ю я ā ą ä á à â å č ć ē ę ě é è ê æ ģ ğ ö ó ø ǿ ô ő ḿ ʼn ń ṕ ŕ ş ü ß ř ł đ þ ĥ ḧ ī ï í î ĵ ķ ł ņ ń ň ř š ś ť ů ú û ứ ù ü ű ū ý ÿ ž ź ż ç є ґ".split(' '); var to= "a b v g d e e zh z i y k l m n o p r s t u f h ts ch sh shch # y # e yu ya a a ae a a a a c c e e e e e e e g g oe o o o o o m n n p r s ue ss r l d th h h i i i i j k l n n n r s s t u u u u u u u u y y z z z c ye g".split(' '); str = str.toLowerCase(); // remove simple HTML tags str = str.replace(/(<[a-z0-9\-]{1,15}[\s]*>)/gi, ''); str = str.replace(/(<\/[a-z0-9\-]{1,15}[\s]*>)/gi, ''); str = str.replace(/(<[a-z0-9\-]{1,15}[\s]*\/>)/gi, ''); str = str.replace(/^\s+|\s+$/gm,''); // trim spaces for(i=0; i<from.length; ++i) str = str.split(from[i]).join(to[i]); // Replace different kind of spaces with dashes var spaces = [/(&nbsp;|&#160;|&#32;)/gi, /(&mdash;|&ndash;|&#8209;)/gi, /[(_|=|\\|\,|\.|!)]+/gi, /\s/gi]; for(i=0; i<from.length; ++i) str = str.replace(spaces[i], '-'); str = str.replace(/-{2,}/g, "-"); // remove special chars like &amp; str = str.replace(/&[a-z]{2,7};/gi, ''); str = str.replace(/&#[0-9]{1,6};/gi, ''); str = str.replace(/&#x[0-9a-f]{1,6};/gi, ''); str = str.replace(/[^a-z0-9\-]+/gmi, ""); // remove all other stuff str = str.replace(/^\-+|\-+$/gm,''); // trim edges return str; }; document.getElementsByTagName('pre')[0].innerHTML = makeSlug(" <br/> &#x202A;Про&amp;вер<strong>ка_тран</strong>с…литеърьации\rюга\nи&ndash;южного&nbsp;округа\t \nс\tёжикам&#180;и&nbsp;со\\всеми&ndash;друзьями\tтоже.Danke schön!ich heiße=КáÞÿá-Skånske,København çağatay rí gé tőr zöldülésetekről - . "); <div> <pre>Hello world!</pre> </div>

对于已经在使用lodash的人

这些例子大多数都很好,涵盖了很多情况。但如果你“知道”你只有英文文本,这是我的版本,非常容易阅读:)

_.words (_.toLower(文本)). join(“-”)

还有一个。短且保留特殊字符:

想象力是丛林=>想象力和丛林

function slugify (text) {
  const a = 'àáäâãèéëêìíïîòóöôùúüûñçßÿœæŕśńṕẃǵǹḿǘẍźḧ·/_,:;'
  const b = 'aaaaaeeeeiiiioooouuuuncsyoarsnpwgnmuxzh------'
  const p = new RegExp(a.split('').join('|'), 'g')

  return text.toString().toLowerCase()
    .replace(/\s+/g, '-')           // Replace spaces with -
    .replace(p, c =>
        b.charAt(a.indexOf(c)))     // Replace special chars
    .replace(/&/g, '-and-')         // Replace & with 'and'
    .replace(/[^\w\-]+/g, '')       // Remove all non-word chars
    .replace(/\-\-+/g, '-')         // Replace multiple - with single -
    .replace(/^-+/, '')             // Trim - from start of text
    .replace(/-+$/, '')             // Trim - from end of text
}

首先,正则表达式不应该有引号,所以'/\s/g'应该是/\s/g

为了用破折号替换所有非字母数字字符,这应该可以工作(使用示例代码):

$("#Restaurant_Name").keyup(function() {
  var Text = $(this).val();
  Text = Text.toLowerCase();
  Text = Text.replace(/[^a-zA-Z0-9]+/g,'-');
  $("#Restaurant_Slug").val(Text);        
});

这应该能奏效……

private string ToSeoFriendly(string title, int maxLength) {
    var match = Regex.Match(title.ToLower(), "[\\w]+");
    StringBuilder result = new StringBuilder("");
    bool maxLengthHit = false;
    while (match.Success && !maxLengthHit) {
        if (result.Length + match.Value.Length <= maxLength) {
            result.Append(match.Value + "-");
        } else {
            maxLengthHit = true;
            // Handle a situation where there is only one word and it is greater than the max length.
            if (result.Length == 0) result.Append(match.Value.Substring(0, maxLength));
        }
        match = match.NextMatch();
    }
    // Remove trailing '-'
    if (result[result.Length - 1] == '-') result.Remove(result.Length - 1, 1);
    return result.ToString();
}