js常用代码片段
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js常用代码片段相关的知识,希望对你有一定的参考价值。
最近会用到的一些公共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常用代码片段的主要内容,如果未能解决你的问题,请参考以下文章