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

这应该能奏效……

其他回答

将这里的答案中的各种元素与normalize结合起来可以提供很好的覆盖率。保持操作的顺序,以增量地清理url。

function clean_url(s) {
    return s.toString().normalize('NFD').replace(/[\u0300-\u036f]/g, "") //remove diacritics
            .toLowerCase()
            .replace(/\s+/g, '-') //spaces to dashes
            .replace(/&/g, '-and-') //ampersand to and
            .replace(/[^\w\-]+/g, '') //remove non-words
            .replace(/\-\-+/g, '-') //collapse multiple dashes
            .replace(/^-+/, '') //trim starting dash
            .replace(/-+$/, ''); //trim ending dash
}

normize ('NFD')将重音字符分解为它们的组成部分,即基本字母加上变音符符号(重音部分)。Replace (/[\u0300-\u036f]/g, "")清除所有变音符,只保留基本字母。其余部分用内联注释解释。

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

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"。

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

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

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

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

<html>

<head>

    <style>

        fieldset.slugify {
            color: #515151;
            border: 1px solid #ccc;
            padding: 15px;
        }

        .slugify legend {
            font-size: 16px;
            font-weight: 600;
            padding: 0 10px;
        }

        .slugify input {
            display: block;
            padding: 8px;
            margin: 8px;
        }

        .slug-output {
            color: #05ab13;
            font-size: 20px;
            font-weight: 500;
        }

    </style>

</head>
 
<body>

    <form>

        <fieldset class="slugify">

            <legend>GeeksforGeeks</legend>

            <label for="slug-source">Input Title: </label>

            <input type="text" value="" id="slug-source" onkeyup="myFunction()" />

            <label for="slug-target">URL Slug: </label>

            <input type="text" value="" id="slug-target" />

            <button type="button" >

                Convert
            </button>       
    
            <p>

                <span class="slug-output">
                    Generated URL Slug
                </span>:

                <span id="slug-target-span"></span>

            </p>

        </fieldset>

    </form>

<script>

    function myFunction() {

        var a = document.getElementById("slug-source").value;

        var b = a.toLowerCase().replace(/ /g, '-')

            .replace(/[^\w-]+/g, '');

        document.getElementById("slug-target").value = b;

        document.getElementById("slug-target-span").innerHTML = b;

    }

</script>

</body>
 
</html>