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

当前回答

首先,正则表达式不应该有引号,所以'/\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();
}

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

    $("#Restaurant_Name").on("keyup", function () {
        var slug = getSlug($("#Restaurant_Name").val());
        $("#Restaurant_Slug").val(slug);
    });

我找到了一个很好的完整的英语解决方案

function slugify(string) {
  return string
    .toString()
    .trim()
    .toLowerCase()
    .replace(/\s+/g, "-")
    .replace(/[^\w\-]+/g, "")
    .replace(/\-\-+/g, "-")
    .replace(/^-+/, "")
    .replace(/-+$/, "");
}

下面是一些使用的例子:

slugify(12345);
// "12345"

slugify("  string with leading   and   trailing whitespace    ");
// "string-with-leading-and-trailing-whitespace"

slugify("mIxEd CaSe TiTlE");
// "mixed-case-title"

slugify("string with - existing hyphens -- ");
// "string-with-existing-hyphens"

slugify("string with Special™ characters");
// "string-with-special-characters"

感谢Andrew Stewart

看完这些答案后,我想到了这个。

const generateSlug = (text) => text.toLowerCase()
                                   .trim()
                                   .replace(/[^\w- ]+/g, '')
                                   .replace(/ /g, '-')
                                   .replace(/[-]+/g, '-');

对于已经在使用lodash的人

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

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