我在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);
});
你可以使用你自己的函数。
试试吧: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;
});
});
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,'');
}
我过滤了两次,因为可能会有更多不需要的字符
我找到了一个很好的完整的英语解决方案
function slugify(string) {
return string
.toString()
.trim()
.toLowerCase()
.replace(/\s+/g, "-")
.replace(/[^\w\-]+/g, "")
.replace(/\-\-+/g, "-")
.replace(/^-+/, "")
.replace(/-+$/, "");
}
下面是一些使用的例子:
slugify(12345);
// "12345"
slugify(" string with leading and trailing whitespace ");
// "string-with-leading-and-trailing-whitespace"
slugify("mIxEd CaSe TiTlE");
// "mixed-case-title"
slugify("string with - existing hyphens -- ");
// "string-with-existing-hyphens"
slugify("string with Special™ characters");
// "string-with-special-characters"
感谢Andrew Stewart
你可以使用你自己的函数。
试试吧: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;
});
});
注意:如果你不关心反对公认答案的论点,只是在寻找答案,那么跳过下一节,你会在最后找到我建议的答案
公认的答案有几个问题(在我看来):
1)对于第一个函数段:
不考虑多个连续的空白
输入:这是一个好鼻涕虫
收到:————————好——蛞蝓
预期:is-it-a-good-slug
不考虑多个连续破折号
输入:————————好——蛞蝓
收到:————————好——蛞蝓
预期:is-it-a-good-slug
请注意,这个实现不处理外部破折号(或空白),无论它们是多个连续的字符还是单数字符(据我所知,以及它们的用法)是无效的
2)对于第二个函数段:
它通过将多个连续的空白转换为单个空白来处理它们——但这还不够,因为外部(字符串的开头和结尾)空白的处理方式是相同的,所以is It -a-good slug将返回-is- It -a-good slug-
它还从输入中完全删除了破虚号,从而将诸如—is—It—a—good—slug—’之类的东西转换为isitaggoodslug, @ryan-allen评论中的代码片段处理了这一点,尽管没有解决外部破虚号问题
now I know that there is no standard definition for slugs, and the accepted answer may get the job (that the user who posted the question was looking for) done, but this is the most popular SO question about slugs in JS, so those issues had to be pointed out, also (regarding getting the job done!) imagine typing this abomination of a URL (www.blog.com/posts/-----how-----to-----slugify-----a-----string-----) or even just be redirected to it instead of something like (www.blog.com/posts/how-to-slugify-a-string), I know this is an extreme case but hey that's what tests are for.
在我看来,更好的解决办法是:
Const slugify = STR =>
str
.trim() //删除字符串开头和结尾的空白
.toLowerCase ()
.replace(/^-+/g, "") //删除字符串开头的一个或多个破折号
.replace(/[^\w-]+/g, "-") //将任意字母数字字符转换为破折号
.replace(/-+/g, "-") //将连续破折号转换为单个破折号
.replace(美元/ - + / g, " ");//删除字符串末尾的一个或多个破折号
现在可能有一个RegExp忍者可以把它转换成一行表达式,我不是RegExp专家,我不是说这是最好的或最紧凑的解决方案,或具有最好的性能,但希望它可以完成工作。
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------";