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

当前回答

String.prototype.slug = function(e='-'){
  let $this=this
        .toUpperCase()
        .toLowerCase()
        .normalize('NFD')
        .trim()
        .replace(/\s+/g,e)
        .replace(/-\+/g,'')
        .replace(/-+/g,e)
        .replace(/^-/g,'')
        .replace(/-$/g,'')
        .replace(/[^\w-]/g,'');
  return $this
        .toUpperCase()
        .toLowerCase()
        .normalize('NFD')
        .trim()
        .replace(/\s+/g,e)
        .replace(/-\+/g,'')
        .replace(/-+/g,e)
        .replace(/^-/g,'')
        .replace(/-$/g,'')
        .replace(/[^\w-]/g,'');
}

我过滤了两次,因为可能会有更多不需要的字符

其他回答

你所需要的只是一个加号:)

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

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

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

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

这应该能奏效……

塔兰蒂尼的答案有点扩展版- https://stackoverflow.com/a/5782563/14431043

var from = "ªºÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿØĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſȘșȚț€£OơƯưẦầẰằỀềỒồỜờỪừỲỳẢảẨẩẲẳẺẻỂểỈỉỎỏỔổỞởỦủỬửỶỷẪẫẴẵẼẽỄễỖỗỠỡỮữỸỹẤấẮắẾếỐốỚớỨứẠạẬậẶặẸẹỆệỊịỌọỘộỢợỤụỰựỴỵɑǕǖǗǘǍǎǏǐǑǒǓǔǙǚǛǜ·/_,:;";
var to = "aoAAAAAAACEEEEIIIIDNOOOOOUUUUYTsaaaaaaaceeeeiiiidnoooooouuuuytyOAaAaAaCcCcCcCcDdDdEeEeEeEeEeGgGgGgGgHhHhIiIiIiIiIiIiJjKkkLlLlLlLlLlNnNnNnnNnOoOoOoOoRrRrRrSsSsSsSsTtTtTtUuUuUuUuUuUuWwYyYZzZzZzsSsTtE--oUuAaAaEeOoOoUuYyAaAaAaEeEeIiOoOoOoUuUuYyAaAaEeEeOoOoUuYyAaAaEeOoOoUuAaAaAaEeEeIiOoOoOoUuUuYyaUuUuAaIiOoUuUuUu------";

接受的答案没有满足我的需求(它允许下划线,在开头和结尾不处理破折号,等等),而其他答案有其他不适合我的用例的问题,所以这里是我想出的slugify函数:

function slugify(string) {
    return string.trim() // Remove surrounding whitespace.
    .toLowerCase() // Lowercase.
    .replace(/[^a-z0-9]+/g,'-') // Find everything that is not a lowercase letter or number, one or more times, globally, and replace it with a dash.
    .replace(/^-+/, '') // Remove all dashes from the beginning of the string.
    .replace(/-+$/, ''); // Remove all dashes from the end of the string.
}

这将把' foo!!BAR_-_-_baz-'(注意开头的空格)变成foo-bar-baz。