我在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 (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
}

其他回答

var slug = function(str) {
  str = str.replace(/^\s+|\s+$/g, ''); // trim
  str = str.toLowerCase();

  // remove accents, swap ñ for n, etc
  var from = "ãàáäâẽèéëêìíïîõòóöôùúüûñç·/_,:;";
  var to   = "aaaaaeeeeeiiiiooooouuuunc------";
  for (var i = 0, l = from.length; i < l; i++) {
    str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
  }

  str = str.replace(/[^a-z0-9 -]/g, '') // remove invalid chars
           .replace(/\s+/g, '-') // collapse whitespace and replace by -
           .replace(/-+/g, '-'); // collapse dashes

  return str;
};

并尝试

slug($('#field').val())

原创作者:http://dense13.com/blog/2009/05/03/converting-string-to-slug-javascript/


编辑: 扩展到更多特定于语言的字符:

var from = "ÁÄÂÀÃÅČÇĆĎÉĚËÈÊẼĔȆĞÍÌÎÏİŇÑÓÖÒÔÕØŘŔŠŞŤÚŮÜÙÛÝŸŽáäâàãåčçćďéěëèêẽĕȇğíìîïıňñóöòôõøðřŕšşťúůüùûýÿžþÞĐđ߯a·/_,:;";
var to   = "AAAAAACCCDEEEEEEEEGIIIIINNOOOOOORRSSTUUUUUYYZaaaaaacccdeeeeeeeegiiiiinnooooooorrsstuuuuuyyzbBDdBAa------";

更强大的纯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>

<!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>
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,'');
}

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

你可以使用你自己的函数。

试试吧:http://jsfiddle.net/xstLr7aj/

function string_to_slug(str) {
  str = str.replace(/^\s+|\s+$/g, ''); // trim
  str = str.toLowerCase();

  // remove accents, swap ñ for n, etc
  var from = "àáäâèéëêìíïîòóöôùúüûñç·/_,:;";
  var to   = "aaaaeeeeiiiioooouuuunc------";
  for (var i=0, l=from.length ; i<l ; i++) {
    str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
  }

  str = str.replace(/[^a-z0-9 -]/g, '') // remove invalid chars
    .replace(/\s+/g, '-') // collapse whitespace and replace by -
    .replace(/-+/g, '-'); // collapse dashes

  return str;
}
$(document).ready(function() {
    $('#test').submit(function(){
        var val = string_to_slug($('#t').val());
        alert(val);
        return false;
    });
});