js驼峰命名转换实现
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript">
window.onload = function(){
function toTF(str){
var tf = str.split('-');
var len = tf.length;
console.log(tf);
for(var i=1; i<len; i++){
var k = tf[i].charAt(0);
k = k.toUpperCase();
tf[i] = tf[i].replace(tf[i].charAt(0),k);
// console.log(tf[i]);
}
console.log(tf);
str = '';
for(var j=0; j<len; j++){
str += tf[j];
}
// console.log(str);
return str;
}
var pt = document.querySelector('input');
var btn = document.querySelector('button');
// console.log(pt)
btn.onclick = function(){
alert('驼峰命名: '+toTF(pt.value));
}
// var kk = toTF("back-aaa-fff-cc-dd-ff-gg");
// console.log(kk)
}
</script>
</head>
<body>
<input type="text" name="" id="" value="background-color" /><button type="button">转驼峰命名</button>
</body>
</html>
修改:简化代码流程
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript">
window.onload = function(){
function toTF(str){
//截断
var tf = str.split('-');
for(var i=1; i<tf.length; i++){
//获取首字母
var k = tf[i].charAt(0);
//修改数组 首字母
tf[i] = tf[i].replace(k,k.toUpperCase());
// console.log(tf[i]);
}
console.log(tf);
//拼接字符
return tf.join('');
}
var pt = document.querySelector('input');
var btn = document.querySelector('button');
// console.log(pt)
btn.onclick = function(){
alert('驼峰命名: '+toTF(pt.value));
}
// var kk = toTF("back-aaa-fff-cc-dd-ff-gg");
// console.log(kk)
}
</script>
</head>
<body>
<input type="text" name="" id="" value="background-color" /><button type="button">转驼峰命名</button>
</body>
</html>
本文来自博客园,作者:JackieDYH,转载请注明原文链接:https://www.cnblogs.com/JackieDYH/p/17634795.html