如何在jQuery中将标题转换为URL slug? [英] How to convert a Title to a URL slug in jQuery?

查看:123
本文介绍了如何在jQuery中将标题转换为URL slug?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用CodeIgniter中的应用程序,我正在尝试在表单上创建一个字段来动态生成URL slug。我想要做的是删除标点符号,将其转换为小写,并用连字符替换空格。例如,Shane的Rib Shack将成为shanes-rib-shack。

I'm working on an app in CodeIgniter, and I am trying to make a field on a form dynamically generate the URL slug. What I'd like to do is remove the punctuation, convert it to lowercase, and replace the spaces with hyphens. So for example, Shane's Rib Shack would become shanes-rib-shack.

这是我到目前为止所拥有的。小写部分很简单,但替换似乎根本不起作用,我不知道删除标点符号:

Here's what I have so far. The lowercase part was easy, but the replace doesn't seem to be working at all, and I have no idea to remove the punctuation:

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


推荐答案

我不知道'slug'一词的来源从,但我们走了:

I have no idea where the 'slug' term came from, but here we go:

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

首先替换会将空格更改为连字符,第二次替换会删除任何不包含字母数字的内容,下划线或者连字符。

First replace will change spaces to hyphens, second replace removes anything not alphanumeric, underscore, or hyphen.

如果你不希望喜欢 - 这个的东西变成喜欢---这个那么你可以改为使用这个:

If you don't want things "like - this" turning into "like---this" then you can instead use this one:

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

这将删除第一次替换时的连字符(但不是空格)第二个替换它会将连续的空格压缩成一个连字符。

That will remove hyphens (but not spaces) on the first replace, and in the second replace it will condense consecutive spaces into a single hyphen.

所以喜欢 - 这个就像喜欢这个。

So "like - this" comes out as "like-this".

这篇关于如何在jQuery中将标题转换为URL slug?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆