標籤:decode format display 類比 mat extension isp [1] 字串格式化
最近會用到的一些公用js,後續會繼續補充。
// string extensions(function () { var fn = String.prototype; fn.format = function () { var args = arguments; return this.replace(/\{(\d+)\}/g, function (m, i) { return args[i] || ""; }); }})();
字串格式化 "name:{0},value:{1}".format("p0","p1") : "name:p0,value:p1"
// json transform
(function (wd) { var transform = function (oldObj, prefix, subObjOrValue, includeFunc) { if (subObjOrValue == null) { oldObj[prefix] = null; } else { if (subObjOrValue instanceof Array) { for (var i = 0; i < subObjOrValue.length; i++) { var newPex = prefix + "[" + i + "]"; transform(oldObj, newPex, subObjOrValue[i], includeFunc); } } else if (typeof subObjOrValue === "object") { for (var name in subObjOrValue) { if (subObjOrValue.hasOwnProperty(name)) { var newObjPex = ""; if (prefix.length === 0) { newObjPex = name + ""; } else { newObjPex = prefix + "." + name; } transform(oldObj, newObjPex, subObjOrValue[name], includeFunc); } } } else { if (includeFunc) { oldObj[prefix] = subObjOrValue; } else { if (typeof subObjOrValue !== "function") { oldObj[prefix] = subObjOrValue; } } } } } wd.JSON.__transformToSimple = function (jsonObj, prefix, includeFunc) { if (!jsonObj) { return null; } var obj = {}; transform(obj, prefix || "", jsonObj, includeFunc); return obj; };})(window);js中 JSON轉換為簡單的JSON,多個層級的json,轉換為只有一個層級的JSON,方便類比表單提交。
{"a":"v-1","b":{"b-1":"v-b1","b-2":"v-b2"},"c":["v-c1","v-c2"]}
轉換為
{"a":"v-1","b.b-1":"v-b1","b.b-2":"v-b2","c[0]":"v-c1","c[1]":"v-c2"}
// html encode or decode(function (wd) { wd.__htmlEncode = function (str) { return ("" + str).replace(/&/g, "&") .replace(/>/g, ">") .replace(/</g, "<") .replace(/ /g, " ") .replace(/\‘/g, "'") .replace(/\"/g, """); }; wd.__htmlDecode = function (str) { return ("" + str).replace(/&/g, "&") .replace(/>/g, ">") .replace(/</g, "<") .replace(/ /g, " ") .replace(/'/g, "\‘") .replace(/"/g, "\""); };})(window);
html編碼,把HTML中的特殊符號編碼,防止幹擾破壞到正常的html。
js常用程式碼片段