这篇文章主要介绍了简单的javascript例子,具有一定借鉴价值,需要的朋友可以参考下。希望大家阅读完这篇文章后大有收获,下面让小编带着大家一起了解一下。
阅读目录
阐述
时间最会骗人,但也能让你明白,这个世界上没有什么是不能失去的,留下的尽力珍惜,得不到的都不重要。
JavaScript 常用实例
字符串操作
去除字符串空格
//去除空格 type 1-所有空格 2-前后空格 3-前空格 4-后空格
function trim(str,type){
switch (type){
case 1:return str.replace(/\s+/g,"");
case 2:return str.replace(/(^\s*)|(\s*$)/g, "");
case 3:return str.replace(/(^\s*)/g, "");
case 4:return str.replace(/(\s*$)/g, "");
default:return str;
}
}
字母大小写切换
/*type
1:首字母大写
2:首页母小写
3:大小写转换
4:全部大写
5:全部小写
* */
//changeCase('asdasd',1)
//Asdasd
function changeCase(str,type)
{
function ToggleCase(str) {
var itemText = ""
str.split("").forEach(
function (item) {
if (/^([a-z]+)/.test(item)) {
itemText += item.toUpperCase();
}
else if (/^([A-Z]+)/.test(item)) {
itemText += item.toLowerCase();
}
else{
itemText += item;
}
});
return itemText;
}
switch (type) {
case 1:
return str.replace(/^(\w)(\w+)/, function (v, v1, v2) {
return v1.toUpperCase() + v2.toLowerCase();
});
case 2:
return str.replace(/^(\w)(\w+)/, function (v, v1, v2) {
return v1.toLowerCase() + v2.toUpperCase();
});
case 3:
return ToggleCase(str);
case 4:
return str.toUpperCase();
case 5:
return str.toLowerCase();
default:
return str;
}
}
字符串循环复制
//repeatStr(str->字符串, count->次数)
//repeatStr('123',3)
//"123123123"
function repeatStr(str, count) {
var text = '';
for (var i = 0; i < count; i++) {
text += str;
}
return text;
}
字符串替换
//字符串替换(字符串,要替换的字符,替换成什么)
function replaceAll(str,AFindText,ARepText){
raRegExp = new RegExp(AFindText,"g");
return str.replace(raRegExp,ARepText);
}
替换 *
//replaceStr(字符串,字符格式, 替换方式,替换的字符(默认*))
function replaceStr(str, regArr, type,ARepText) {
var regtext = '', Reg = null,replaceText=ARepText||'*';
//replaceStr('18819322663',[3,5,3],0)
//188*****663
//repeatStr是在上面定义过的(字符串循环复制),大家注意哦
if (regArr.length === 3 && type === 0) {
regtext = '(\\w{' + regArr[0] + '})\\w{' + regArr[1] + '}(\\w{' + regArr[2] + '})'
Reg = new RegExp(regtext);
var replaceCount = repeatStr(replaceText, regArr[1]);
return str.replace(Reg, '$1' + replaceCount + '$2')
}
//replaceStr('asdasdasdaa',[3,5,3],1)
//***asdas***
else if (regArr.length === 3 && type === 1) {
regtext = '\\w{' + regArr[0] + '}(\\w{' + regArr[1] + '})\\w{' + regArr[2] + '}'
Reg = new RegExp(regtext);
var replaceCount1 = repeatSte(replaceText, regArr[0]);
var replaceCount2 = repeatSte(replaceText, regArr[2]);
return str.replace(Reg, replaceCount1 + '$1' + replaceCount2)
}
//replaceStr('1asd88465asdwqe3',[5],0)
//*****8465asdwqe3
else if (regArr.length === 1 && type == 0) {
regtext = '(^\\w{' + regArr[0] + '})'
Reg = new RegExp(regtext);
var replaceCount = repeatSte(replaceText, regArr[0]);
return str.replace(Reg, replaceCount)
}
//replaceStr('1asd88465asdwqe3',[5],1,'+')
//"1asd88465as+++++"
else if (regArr.length === 1 && type == 1) {
regtext = '(\\w{' + regArr[0] + '}$)'
Reg = new RegExp(regtext);
var replaceCount = repeatSte(replaceText, regArr[0]);
return str.replace(Reg, replaceCount)
}
}
检测字符串
//checkType('165226226326','phone')
//false
//大家可以根据需要扩展
function checkType (str, type) {
switch (type) {
case 'email':
return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str);
case 'phone':
return /^1[3|4|5|7|8][0-9]{9}$/.test(str);
case 'tel':
return /^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/.test(str);
case 'number':
return /^[0-9]$/.test(str);
case 'english':
return /^[a-zA-Z]+$/.test(str);
case 'chinese':
return /^[\u4E00-\u9FA5]+$/.test(str);
case 'lower':
return /^[a-z]+$/.test(str);
case 'upper':
return /^[A-Z]+$/.test(str);
default :
return true;
}
}
检测密码强度
//checkPwd('12asdASAD')
//3(强度等级为3)
function checkPwd(str) {
var nowLv = 0;
if (str.length < 6) {
return nowLv
}
if (/[0-9]/.test(str)) {
nowLv++
}
if (/[a-z]/.test(str)) {
nowLv++
}
if (/[A-Z]/.test(str)) {
nowLv++
}
if (/[\.|-|_]/.test(str)) {
nowLv++
}
return nowLv;
}
随机码(toString详解)
//count取值范围0-36
//randomNumber(10)
//"2584316588472575"
//randomNumber(14)
//"9b405070dd00122640c192caab84537"
//Math.random().toString(36).substring(2);
//"83vhdx10rmjkyb9"
function randomNumber(count){
return Math.random().toString(count).substring(2);
}
查找字符串次数
function countStr (str,strSplit){
return str.split(strSplit).length-1
}
var strTest='sad44654blog5a1sd67as9dablog4s5d16zxc4sdweasjkblogwqepaskdkblogahseiuadbhjcibloguyeajzxkcabloguyiwezxc967'
//countStr(strTest,'blog')
//6
其他操作
cookie
//cookie
//设置cookie
function setCookie(name,value,iDay){
var oDate=new Date();
oDate.setDate(oDate.getDate()+iDay);
document.cookie=name+'='+value+';expires='+oDate;
}
//获取cookie
function getCookie(name){
var arr=document.cookie.split('; ');
for(var i=0;i<arr.length;i++){
var arr2=arr[i].split('=');
if(arr2[0]==name)
{
return arr2[1];
}
}
return '';
}
//删除cookie
function removeCookie(name){
setCookie(name,1,-1);
}
清除对象中值为空的属性
//filterParams({a:"",b:null,c:"010",d:123})
//Object {c: "010", d: 123}
function filterParams(obj){
let _newPar = {};
for (let key in obj) {
if ((obj[key] === 0 || obj[key]) && obj[key].toString().replace(/(^\s*)|(\s*$)/g, '') !== '') {
_newPar[key] = obj[key];
}
}
return _newPar;
}
现金额大写转换函数
<>
//upDigit(168752632)
//"人民币壹亿陆仟捌佰柒拾伍万贰仟陆佰叁拾贰元整"
//upDigit(1682)
//"人民币壹仟陆佰捌拾贰元整"
//upDigit(-1693)
//"欠人民币壹仟陆佰玖拾叁元整"
function upDigit(n)
{
var fraction = ['角', '分','厘'];
var digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
var unit = [ ['元', '万', '亿'], ['', '拾', '佰', '仟'] ];
var head = n < 0? '欠人民币:': '人民币:';
n = Math.abs(n);
var s = '';
for (var i = 0; i < fraction.length; i++)
{
s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
}
s = s || '整';
n = Math.floor(n);
for (var i = 0; i < unit[0].length && n > 0; i++)
{
var p = '';
for (var j = 0; j < unit[1].length && n > 0; j++)
{
p = digit[n % 10] + unit[1][j] + p;
n = Math.floor(n / 10);
}
//s = p.replace(/(零.)*零$/, '').replace(/^$/, '零')+ unit[0][i] + s;
s = p+ unit[0][i] + s;
}
return head + s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整');
}
console.log(upDigit(-123456789));
</>
获取,设置 url 参数
//获取url参数
//getUrlPrmt('segmentfault.com/write?draftId=122000011938')
//Object{draftId: "122000011938"}
function getUrlPrmt(url) {
url = url ? url : window.location.href;
let _pa = url.substring(url.indexOf('?') + 1), _arrS = _pa.split('&'), _rs = {};
for (let i = 0, _len = _arrS.length; i < _len; i++) {
let pos = _arrS[i].indexOf('=');
if (pos == -1) {
continue;
}
let name = _arrS[i].substring(0, pos), value = window.decodeURIComponent(_arrS[i].substring(pos + 1));
_rs[name] = value;
}
return _rs;
}
//设置url参数
//setUrlPrmt({'a':1,'b':2})
//a=1&b=2
function setUrlPrmt(obj) {
let _rs = [];
for (let p in obj) {
if (obj[p] != null && obj[p] != '') {
_rs.push(p + '=' + obj[p])
}
}
return _rs.join('&');
}
随机返回一个范围的数字
function randomNumber(n1,n2){
//randomNumber(5,10)
//返回5-10的随机整数,包括5,10
if(arguments.length===2){
return Math.round(n1+Math.random()*(n2-n1));
}
//randomNumber(10)
//返回0-10的随机整数,包括0,10
else if(arguments.length===1){
return Math.round(Math.random()*n1)
}
//randomNumber()
//返回0-255的随机整数,包括0,255
else{
return Math.round(Math.random()*255)
}
}