首页 > 代码库 > js常用代码片段
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 =http://www.mamicode.com/= 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 =http://www.mamicode.com/=="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常用代码片段
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。