1、将一段字符串转成驼峰命名法。
var str = "web-kit-index";
function to(str){
var j = str.split("-");
for(var i=1,len=j.length;i<len;i++){
j[i] = j[i].charAt(0).toUpperCase()+j[i].substring(1);
}
return j.join("");
}
console.log(to(str));
或
function to(str){
var reg = /-(w)/g;
return str.replace(reg,function(a,b){
return b.toUpperCase();
})
}
console.log(to(str));
2、判断一段字符串中出现最多的是哪个字符并且出现了多少次?
var str = "wwwwaaaa";
function max(str){
var obj = {};
for(var i=0,len=str.length;i<len;i++){
if(!obj[str[i]]){
obj[str[i]] = [];
obj[str[i]].push(str[i]);
}else{
obj[str[i]].push(str[i]);
}
}
var num = 0,value;
for(var k in obj){
if(obj[k].length>num){
num = obj[k].length;
value = k;
}
}
return "出现最多的是:"+obj[value][0]+" 出现了:"+num+"次";
}
console.log(max(str));
或
function max(str){
var s = str.split("").sort().join("");
var reg = /(w)1+/g;
var num = 0;
var value = null;
s.replace(reg,function($0,$1){
if(num<$0.length){
num = $0.length;
value = $1;
}
})
return "出现最多的是:"+value+" 出现了:"+num+"次";
}
console.log(max(str));
3、如果有数组,把他们添加到数组中,并且如果是连续的数字那么把它们添加到一起
var str = "js123werw13weragadsg324ererrer5555";
var num = '';
var arr = [];
for(var i=0;i<str.length;i++){
if(!isNaN(+str[i])){
num += str[i];
if(isNaN(+str[i+1])){
arr.push(+num);
num = "";
}
}
}
console.log(arr);
4、给字符串加千分符,每三位加一个,
var str = "13224242311012101";
function san(){
var first = (str.length)%3;
var s = str.substring(0,first);
var reg = str.substring(first);
var arr = [];
if(first!==0){
arr.push(s);
}
var t = "";
for(var i=0;i<reg.length;i++){
t+=reg[i];
if(i%3===2){
arr.push(t);
t = "";
}
}
return arr.join(",");
}
console.log(san(str));
function san(str){
var reg = /(?=(?!)(d{3})+$)/g;
return str.replace(reg,",");
}
console.log(san(str));
5、交换两个字符串的位置,不允许第三个变量
var a = 12;
var b = 20;
a = a + b;
b = a - b;
a = a - b;
console.log(a);
console.log(b);
或
var str1 = 'love';
var str2 = 'Js';
str1 = [str1,str2];
str2 = str1[0];
str1 = str1[1];
console.log(str1);
console.log(str2);
方法1:只支持数字
6、不使用for循环实现一个数字的数组排序。
var num = 10;
function a(num){
var arr = [];
return (function(){
arr.unshift(num);
num--;
if(num!=0){
arguments.callee();
}
return arr;
}());
}
console.log(a(num)); [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
function a(num){
var arr = [];
arr.length = num+1;
arr = arr.join("a");
var arr2 = [];
arr.replace(/a/g,function(){
arr2.unshift(num--);
})
return arr2;
}
console.log(a(num)); [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
7、打乱数组值的顺序
var arr = [1, 2, 3, 4, 5, 6, 7, 8];
function sort(arr){
for(var i=0;i<arr.length-1;i++){
var cur = Math.floor(Math.random()*(i+1));
var tel = arr[i];
arr[i] = arr[cur];
arr[cur] = tel;
}
return arr;
}
console.log(sort(arr));