javascript-如何增强Slugify来处理Camel Case?
作者:互联网
我想将JavaScript函数编写为slugify a string,还有一个要求:处理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’以查找所有大写字母,而不仅仅是第一个大写字母.
标签:camelcasing,slug,javascript,regex 来源: https://codeday.me/bug/20191201/2083724.html