工做中經常使用的JS函數整理分享(歡迎你們補充)

今年在渣X工做整理的經常使用JS函數

今年來了渣X工做,我所在這個部門分工很奇怪,CSS居然有專門的人在搞,開發PHP的人員須要處理JS,以致於有時候開發起來不是那麼駕輕就熟,感受把JS和CSS拆開就像是把方向盤、油門分別交給了兩我的來控制,兩我的都很不得勁。再說說這邊的js吧,徹底是那種複製粘貼的方式,更別說使用什麼新的前端工具來進行各類優化了。到目前爲止,我作了一件事情,將公共經常使用的JS拆出來,避免複製粘貼去使用,提升開發效率、提升代碼魯棒性。但仍是拿出來分享給你們,順便記錄下。前端

基礎工具Tools

/path/to/Tools.js數組

"use strict";
function Tools(){

};

正則批量替換

正則批量替換,支持多組規則。瀏覽器

/**
 * 
 * @param  string str   待處理的字符串
 * @param  array trans 要替換的規則列表
 * @return string      替換以後的字符串
 */
Tools.prototype.regA2B = function(str, trans) {
	var i, re, to;
	for (i in trans) {
		re = trans[i][0];
		to = trans[i][1];
		str = str.replace(re, to);
	}
	return str;
};

看看下面的例子函數

var str = " 你好 		;‘’「」()——,\n\n";
var formatStr = tools.regA2B(str, [
  	[/^\s+|\s+$/gm, ""],
  	[/(\r\n)|(\t)/gm, ""],
  	[/(/gm, "("],
	[/)/gm, ")"],
  	[/「|」/gm, "\""],
  	[/‘|’/gm, "'"],
  	[/,/gm, ","],
  	[/;/gm, ";"],
  	[/:/gm, ":"],
  	[/——/gm, "-"]
]);
console.log(formatStr);

上面的例子輸出你好 ;''""()-,,這裏必定要注意替換的順序,會按照參數trans中數組的順序依次替換。工具

字符串格式化

格式換字符串中的制定變量優化

/**
 * 
 * @param  string str     帶格式換變量
 * @param  Object formats 替換變量的映射
 * @return string         替換以後的字符串
 */
Tools.prototype.formatString = function(str, formats) {
    var i, re;
    for (i in formats) {
    	re = new RegExp("\\{" + i + "\\}", "gm");
    	str = str.replace(re, formats[i]);
    }
    return str;
};

看例子:編碼

var str = "你好{name},我今年{age}歲";
var formatStr = tools.formatString(str, {
	name: "葉榮添",
	age: 26
});
console.log(formatStr);

上面的例子輸出你好葉榮添,我今年26歲url

獲取連接參數

從瀏覽器地址欄中的連接或制定連接中獲取參數的值spa

/**
 * 從瀏覽器連接參數中獲取參數值
 * 
 * @param  	string name 待獲取的參數名
 * @param 	undefined|string url      制定連接
 * @return string|null
 */
Tools.prototype.getQueryString = function(name, url) { 
	url = typeof(url) != "string" ? window.location.search : url;
	var reg = new RegExp("(\\?|&)" + name + "=([^&]*)(&|$)", "i"); 
	var r = url.match(reg); 
	if (r != null) {
		return decodeURIComponent(r[2]);
	} else {
		return null;
	}
};

看例子prototype

var url = "https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=0";
var val = tools.getQueryString("ie", url);
console.log(val);

上面的例子輸出utf-8

格式化URL參數

格式化URL參數,能夠給URL中添加參數和修改參數

/**
 * @param  string url    待處理的URL
 * @param  object params 要設置的參數映射map
 * @param  bool isEncode 是否使用encodeURIComponent對參數進行編碼
 * @return string        處理以後的url
 */
Tools.prototype.formatUrlParams = function(url, params, isEncode) {
	var splitByHash, pureUrl, hashInfo = ""
	, i, reg;
	if(typeof(isEncode) == "undefined") {
		isEncode = true;
	}
	// 參數校驗
	if (typeof(url) != "string") {
		throw "要格式化的url必須是字符串";
	}
	splitByHash = url.split("#");
	if (splitByHash.length > 2) {
		throw "要格式化的url中最多有一個#hash";
	}
	pureUrl = splitByHash[0];
	if (splitByHash.length == 2) {
		hashInfo = "#" + splitByHash[1];
	}

	for (i in params) {
		reg =  new RegExp("(^|)"+ i +"=([^&]*)(|$)");
		if (pureUrl.match(reg) != null) {
			pureUrl = pureUrl.replace(
				reg, 
				i+"="+ (isEncode ? encodeURIComponent(params[i]) : params[i])
			);
		} else {
			if (pureUrl.match(/\?/g) != null) {
				pureUrl = pureUrl + "&" + i + "=" + (isEncode ? encodeURIComponent(params[i]) : params[i]);
			} else {
				pureUrl = pureUrl + "?" + i + "=" + (isEncode ? encodeURIComponent(params[i]) : params[i]);
			}
		}
	}

	pureUrl += hashInfo;

	return pureUrl;
};

看例子

var url = "https://weibo.com/u/5824742984/home?wvr=5#where";
formatUrl = tools.formatUrlParams(url, {
	age: 26,
	name: "葉榮添",
	where: "homepage",
	wvr: 123
});
console.log(formatUrl);

上面的例子輸出https://weibo.com/u/5824742984/home?wvr=123&age=26&name=%E7%87%95%E7%9D%BF%E6%B6%9B&where=homepage#where

正則校驗參數

匹配字符串中的字符是否全是給定的選擇類型

  • zh: 表示漢子,
  • en: 表示大小寫字母
  • 其餘的用戶傳入的會加入字符串匹配中
/**
 * 	
 * @param  string text  待校驗的參數
 * @param  array types 	校驗的規則
 * @param  int min 		最小長度
 * @param  int max		最大長度
 * @return bool       	是否校驗經過
 */
Tools.prototype.checkChar = function(text, types, min, max) {
	var typeRegs, i, reg, regObj, ret, scope;
	if ("undefined" == typeof(min)) {
		if ("undefined" == typeof(max)) {
			scope = "+";
		} else {
			scope = "{,"+max+"}";
		}
	} else {
		if (parseInt(min) < 0) {
			throw "字符串長度最小值應該是大於等於0的整數";
		}
		min = parseInt(min);
		scope = "{"+min+",";
		if ("undefined" == typeof(max)) {
			scope += "}";
		} else {
			if(
				parseInt(max) < 0 ||
				parseInt(max) < min
			) {
				throw "字符串長度最小值應該是大於等於0的整數,且應該大於等於最小長度";
			}
			max = parseInt(max);
			scope += max + "}";
		}
	}

	var typeRegs = {
		"zh": "[\u4e00-\u9fa5]",
		"en": "[a-zA-Z]"
	},
	i, reg, regObj, ret;

	types = types ? types : ["zh", "en"];
	reg = "^("
	for (i=0; i<types.length; i++) {
		if (!typeRegs[types[i]]) {
			reg += types[i] + "|";
		} else {
			reg += typeRegs[types[i]] + "|";
		}
	}
	reg = reg.substr(0, reg.length - 1);
	reg += ")"+scope+"$";
	//console.log(reg);
	// 打印正則
	regObj = new RegExp(reg);

	ret = regObj.test(text);

	return ret ? true : false;
};

看例子:

tools.checkChar("葉榮添", false, 3);
// 輸出true

tools.checkChar("葉榮添", false, 5, 10);
// 輸出false

tools.tools.checkChar("葉榮添a-_   \\sdASS ", ["zh", "en", "[_\\- ]", "[\\\\]"]);
// 輸出true
相關文章
相關標籤/搜索