我目前正在获取 location.path
网址并将该网址显示为我的标题,如果我有“香蕉和苹果”之类的标题,我如何才能将其设为驼峰式呢?希望“and”为“And”,但只返回“Banana and Apple”
我找到了这段 JavaScript 代码,它返回了我的标题“Banana And Apple”。
function camelize(str) {
return str.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, function(match, index) {
if (+match === 0) return " "; // or if (/\s+/.test(match)) for white spaces
return index == 0 ? match.toLowerCase() : match.toUpperCase();
});
}
我将 (/) 和 (-) 替换为空格
this.title = camelize(lastPartOfUrl.replace(/\/|\-/g, ' '));
或
var cleanUrl = lastPartOfUrl.replace(/\/-/g, ' ');
this.title = camelize(cleanUrl.replace(/-/g, ' '));
最佳答案
有基于单个正则表达式的更短的解决方案。
function camelCase(txt){
var lower='and,or,a,in,on,'; //stop-words
return txt //.split(/\/-/).join(' ')
.toLowerCase().replace(/(\b.)(\S*\b)(\s|$)/g,
function(m/*full match*/,
n/*(\b.)*/,
p/*(\S*\b)*/,
q/*(\s|$)*/){
//console.log(n,p);
return (lower.indexOf(n+p+',')===-1?
n.toUpperCase() : n) + p + q;});
}
关于javascript 正则表达式 驼峰式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38833945/