js写的替换字符串(相当于js操作字符串的一个练习)
1.达到的效果
1./main_1.do,/left_1.do -> main:1,left:1
2./tbl_type/v_list_{id}.do -> tbl_type:list:{id}
3./tmd/v_list.do -> tmd:list
2.代码
/* * 修改菜单URI自动设置权限URI */ function autoSetMenuPermission() { var permission = document.getElementsByName("menuPermission")[0]; var menuUri = document.getElementsByName("menuUri")[0].value; var perUri; if (menuUri.indexOf(",") != -1) { var uriArr = menuUri.split(","); var perUriArr = new Array(); for (x in uriArr) { perUriArr.push(removeUnderLine(uriArr[x])); } perUri = perUriArr.toString(); } else { perUri = removeUnderLine(menuUri); } permission.value = perUri; } /* * 1./main_1.do,/left_1.do main:1 * 2./tbl_type/v_list_{id}.do tbl_type:list:{id} * 3./tmd/v_list.do tmd:list */ function removeUnderLine(str) { str = str.replace(".do","").replace("/",""); var index_backslash = str.indexOf("/"); if (index_backslash != -1) { var arry = str.split("/"); var name = arry[0]; var oper = arry[1]; // alert(oper); if (oper.indexOf("_")!=-1) { var operArr = oper.split("_"); switch (operArr.length) { case 2: // aa = oper.replace("_",":"); prefix = oper.substr(0,1); // alert(prefix); endfix = oper.substr(oper.indexOf("_")+1); if (prefix == "o") { if (endfix == 'add') { endfix = 'save'; }else if(endfix == 'edit'){ endfix = 'update'; } } return name+":"+endfix; break; case 3: if (operArr[2] == 'order') { aa = oper.substr(oper.indexOf("_")+1); } else { aa = oper.substr(oper.indexOf("_")+1).replace("_",":"); } // alert(aa); return name+":"+aa; break; default: break; } }else{ return name+":"+oper; } } else { var index = str.indexOf("_"); if (index != -1) { if (isNaN(str.substr(index + 1))) { return str.substr(index + 1); } else { return str.replace("_",":"); } } else { return str; } } }