写一个字符串转成驼峰的方法
var str = 'boder-bottom-color';
function test(str) {
var arr = str.split('-');
for(var i = 1; i<arr.length;i++ ) {
arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].substring(1);
}
return arr.join('-')
}
function test1(str) {
var re = /-(\w)/g;
return str.replace(re, function($0,$1) {
return $1.toUpperCase();
})
}
复制代码
查找字符串中出现最多的字符和次数
var str = 'sdjksfssscfssdd';
function test(str) {
var obj = {};
var num = 0;
var value = '';
for(var i = 0; i<str.length; i++) {
if(!obj[str[i]]) {
obj[str[i]] = []
}
obj[str[i]].push(str[i]);
}
for(var attr in obj) {
if(num < obj[attr].length) {
num = obj[attr].length;
value = obj[attr][0];
}
}
return '最多的字符是'+ value + ', 出现了:' + num;
}
function test1(str) {
var arr = str.split('');
arr.sort();
str = arr.join('');
var num = 0;
var value = '';
var re = /(\w)\1+/g;
str.replace(re, function ($0, $1) {
console.log($0, $1)
if (num < $0.length) {
num = $0.length
value = $1;
}
})
return '最多的字符是' + value + ', 出现了:' + num;
}
复制代码
如何给字符串加上千分符号
var iNum = str.length%3;
var prev = '';
var arr = [];
var iNow = 0;
var tmp = '';
if(iNum !==0) {
prev = str.substring(0,iNum)
arr.push(prev)
};
str = str.substring(iNum)
for(var i = 0; i<str.length;i++) {
iNow++;
tmp+= str[i]
if(iNow == 3 && tmp) {
arr.push(tmp);
tmp = '';
iNow = 0;
}
}
return arr.join(',')
}
function test2(str) {
var re = /(?=(?!\b)(\d{3})+$)/g;
return str.replace(re,',')
}
复制代码
返回一个只包含数字类型的数组
var str = 'js123ldka78sdassdfd653';
var re = /\d+/g;
var arr = [];
str.replace(re,function($0,$1) {
arr.push(Number($0))
})
还别的方法,你来
复制代码