我在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){
return text.toString().toLowerCase()
.replace(/\s+/g, '-') // Replace spaces with -
.replace(/[^\u0100-\uFFFF\w\-]/g,'-') // Remove all non-word chars ( fix for UTF-8 chars )
.replace(/\-\-+/g, '-') // Replace multiple - with single -
.replace(/^-+/, '') // Trim - from start of text
.replace(/-+$/, ''); // Trim - from end of text
}
*基于https://gist.github.com/mathewbyrne/1280286
现在你可以转换这个字符串:
Barack_Obama Барак_Обама ~!@#$%^&*()+/-+?><:";'{}[]\|`
成:
barack_obama-барак_обама
应用于你的代码:
$("#Restaurant_Name").keyup(function(){
var Text = $(this).val();
Text = slugify(Text);
$("#Restaurant_Slug").val(Text);
});
更强大的纯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 = [/( | | )/gi, /(—|–|‑)/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 &
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/> ‪Про&вер<strong>ка_тран</strong>с…литеърьации\rюга\nи–южного округа\t \nс\tёжикам´и со\\всеми–друзьями\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>
接受的答案没有满足我的需求(它允许下划线,在开头和结尾不处理破折号,等等),而其他答案有其他不适合我的用例的问题,所以这里是我想出的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。
我不知道“鼻涕虫”这个词从何而来,但我们开始吧:
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"。