我想为 slugify a string 编写一个 JavaScript 函数,还有一个要求:处理 Camel Case。例如,thisIsCamelCase
将变为 this-is-camel-case
。
如何修改 function like this这样做?
编辑
添加完整,answered example .
最佳答案
你只需要在你发布的内容中添加一行代码
str = str.replace(/[A-Z]/g, function(s){ return "-" + s; });
这使得剩下的代码成为
function string_to_slug(str) {
str = str.replace(/^\s+|\s+$/g, ''); // trim
str = str.replace(/[A-Z]/g, function(s){ return "-" + s; }); // camel case handling
str = str.toLowerCase();
// remove accents, swap ñ for n, etc
var from = "àáäâèéëêìíïîòóöôùúüûñç·/_,:;",
to = "aaaaeeeeiiiioooouuuunc------";
for (var i=0, l=from.length ; i<l ; i++) {
str = str.replace(from[i], to[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;
}
编辑::我也删除了无用的新 RegExp 逻辑。 编辑::添加 'g' 以查找所有大写字母,而不仅仅是第一个。
关于javascript - 如何增强 slugify 以处理 Camel Case?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8991908/