前端学习(1818):前端面试题之封装函数之进行字符串驼峰的命名

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>

	<body>
		<script type="text/javascript">
			//已知有字符串foo='get-element-by-id',写一个function将其转化成驼峰表示法”getElementById”

			//自定义函数
			function toString(foo) {
//				var foo = 'get-element-by-id';
				//根据某个字符进行切割
				var arr = foo.split('-');
				//获取每个元素中的第一个字符并转换成大写
				console.log(arr[1].charAt(0).toUpperCase() + arr[1].substr(1, arr[1].length - 1));
				for(var i = 1; i < arr.length; i++) {

					arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].substr(1, arr[i].length - 1)
				}
				//根据某个字符将数组转成字符串
				return arr.join('');
			}
			
		 	console.log(toString('get-element-by-id'));
		</script>
	</body>

</html>

运行结果

猜你喜欢

转载自blog.csdn.net/weixin_43392489/article/details/107498261