- 查找数字
原生
找出字符串中的数字
(function(){
function num(str) {
let arr = [];
let temp = '';
for(let i = 0; i < str.length; i++) {
if(str.charAt(i) <= '9' && str.charAt(i) >= '0') {
//arr.push(str.charAt(i))
temp += str.charAt(i);
}
else {
if(temp){
arr.push(temp);
temp = ''; } } }
if(temp){
arr.push(temp);
}
console.log(arr)
}
let str = '123asf434sf43621wq345';
num(str);
})();
正则表达式 /\d+/g
let str1 = '123asf434sf43621wq345';
let re = /\d+/g;
console.log(str.match(re))
- 敏感词过滤
(function () {
let str = '嘿嘿中国呵呵呵少年sp';
let re = /嘿嘿|呵呵呵|sp/g;
let result = str.replace(re,function (str0,str1,str2,str3) {
let temp = '';
if(str){
for(let i = 0; i < str.length; i++){
temp+='*'
} }
// console.log(temp)
return temp;
});
console.log(result); //**中国***少年**
})();
- 找出重复次数最多的字符以及次数
(function(){
// let str = 'asdaaassseedddddaffgyDXCvSSS';
let str = 'aSdv';
let re = /(\w)\1*/ig;
//将字符串进行排序,把相同的字符放在一起
let arr = str.toLowerCase().split('');
// console.log(arr)
str = arr.sort().join('');
// console.log(str)
let MaxLen = 0;
let MaxValue = '';
str.replace(re,function($0,$1,$2,$3,$4){
console.log(arguments)
if($0.length > MaxLen) {
MaxLen = $0.length;
MaxValue = $1;
}else if($0.length === MaxLen){MaxValue += $1}
})
console.log(MaxValue+'.....'+MaxLen)
})();
- 去掉空格
(function(){
let str = ' as as d ';
// let re = /^\s|\s/g; //去除全部空格
let re = /^\s+|\s+$/g; //去除首尾空格
console.log('('+str.replace(re,'')+')')
})()
trim用法
网友评论