我在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);  
});

当前回答

function slugify(content) {
   return content.toLowerCase().replace(/ /g,'-').replace(/[^\w-]+/g,'');
}
// slugify('Hello World');
// this will return 'hello-world';

这对我来说很好。

在CodeSnipper上找到的

其他回答

你可能想看看speakingURL插件,然后你就可以:

    $("#Restaurant_Name").on("keyup", function () {
        var slug = getSlug($("#Restaurant_Name").val());
        $("#Restaurant_Slug").val(slug);
    });
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();
}

我不知道“鼻涕虫”这个词从何而来,但我们开始吧:

function convertToSlug(Text) {
  return Text.toLowerCase()
             .replace(/ /g, '-')
             .replace(/[^\w-]+/g, '');
}

第一个replace方法将空格更改为连字符,第二,replace删除除字母数字、下划线或连字符以外的任何内容。

如果你不希望“like- this”变成“like- this”,你可以用这个:

function convertToSlug(Text) {
  return Text.toLowerCase()
             .replace(/[^\w ]+/g, '')
             .replace(/ +/g, '-');
}

这将在第一次替换时删除连字符(但没有空格),在第二次替换时将连续的空格压缩为单个连字符。

所以"like-this"就变成了"like-this"。

对于已经在使用lodash的人

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

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

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

/* 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>