我有一个下一个字符串:
$scope.string = "User {{User Firstname}} </p><p>System {{Reported System Name}} </p><p>Desc {{Description}}</p><ol></ol>"
我正在努力实现下一个结果:
$scope.string = "User {{userFirstname}} </p><p>System {{reportedSystemName}} </p><p>Desc {{description}}</p><ol></ol>"
借助正则表达式,我可以找到camelize text
所必需的if ($scope.string.match(/\{\{(.*?)\}\}/g)){
for (var i = 0; i < $scope.string.match(/\{\{(.*?)\}\}/g).length; i ++){
$scope.string.match(/\{\{(.*?)\}\}/g)[i] = camelizeBrackets($scope.string.match(/\{\{(.*?)\}\}/g)[i])
}
}
但我找到here并修改为使用大括号内的文本的函数camelizeBrackets
根本不起作用
function camelizeBrackets(str) {
return str.replace(/\{\{(?:^\w|[A-Z]|\b\w|\s+)\}\}/g, function(match, index) {
if (+match === 0) return "";
return index === 0 ? match.toLowerCase() : match.toUpperCase();
});
}
有人可以解释我的错误吗?
答案 0 :(得分:1)
你可以分2步完成,得到内部括号内容,然后将其加入。
(注意 - 如果只有你的话,你可以用空格\W
替换 not-word \s
想要删除空格)
解释
^ \W*
( \w ) # (1), First letter of first word
| # or,
\b
( \w ) # (2), First letter of other words
| # or,
( \W ) # (3), Non-words, whitespace, etc...
function camelize(str)
{
return str.replace( /^\W*(\w)|\b(\w)|(\W)/g,
function(match, g1,g2,g3) {
if ( g1 != null ) // first word, first letter
return g1.toLowerCase();
else
if ( g2 != null ) // second word's, first letter
return g2.toUpperCase();
return ''; // all non-word letters( wsp )
}
)
}
function camelizeBrackets(str)
{
return str.replace(/\{\{([\S\s]*?)\}\}/g,
function(match, g1) {
return '{{' + camelize( g1 ) + '}}';
}
);
}
console.log( camelizeBrackets("{{EquipmentClass name}}") );
console.log( camelizeBrackets("{{Equipment className}}") );
console.log( camelizeBrackets("{{equipment class name}}") );
console.log( camelizeBrackets("{{Equipment Class Name}}") );
console.log( camelizeBrackets("User {{User Firstname}} </p><p>System {{Reported System Name}} </p><p>Desc {{Description}}</p><ol></ol>") );
所有输出{{equipmentClassName}}
与
User {{userFirstname}} </p><p>System {{reportedSystemName}} </p><p>Desc {{description}}</p><ol></ol>
在末尾。