2012年3月11日星期日

使用JavaScript正则表达式实现一些实用函数


  1. //去除字符串空格  
  2. /*** Start of Modify ***/  
  3. function ltrim(str){  
  4.     /* Trims leading spaces - returns string 
  5.      * Returns trimmed string 
  6.      */  
  7.     return str.replace(/^\s+/, '');  
  8. }//eof - ltrim  
  9.   
  10. function rtrim(str) {  
  11.     /* Trims trailing spaces - returns string 
  12.      * Returns trimmed string 
  13.      */  
  14.     return str.replace(/\s+$/, '');  
  15. }//eof - rtrim  
  16.   
  17. function alltrim(str) {  
  18.     /* Trims leading and trailing spaces 
  19.      * Returns trimmed string 
  20.      */  
  21.     return str.replace(/^\s+|\s+$/g, '');  
  22. }//eof - alltrim  
  23.   
  24. //填充
  25. function padleft(str, ch, num) {  
  26.     /* Pads string on left with number characters 
  27.      * Args: 
  28.      *    str = string to pad 
  29.      *    ch = pad character 
  30.      *    num = number of total characters in final string 
  31.      * returns string 
  32.      */  
  33.     ch = ch || " "//otherwise pad.length remains 0.  
  34.       
  35.     //Create pad string num chars  
  36.     var pad = "";  
  37.     do  {  
  38.         pad += ch;  
  39.     } while(pad.length < num);  
  40.   
  41.     //Regular express take num chars from right  
  42.     var re = new RegExp(".{" + num + "}$")[0];  
  43.   
  44.     return re.exec(pad + str);  
  45. }//eof - padleft  
  46.   
  47. function padright(str, ch, num){  
  48.     /* Pads string on right with number characters 
  49.      * Args: 
  50.      *    str = string to pad 
  51.      *    ch = pad character 
  52.      *    num = number of total characters in final string 
  53.      * returns string 
  54.      */  
  55.     ch = ch || " "//otherwise pad.length remains 0.  
  56.   
  57.     //Create pad string num chars  
  58.     var pad = "";  
  59.     do {  
  60.         pad += ch;  
  61.     } while (pad.length < num);  
  62.   
  63.     //Regular express take num chars from left  
  64.     var re = new RegExp("^.{" + num + "}");  
  65.     return re.exec(str + pad)[0];  
  66. }//eof - padright  
  67.   
  68. function padcenter(str, ch, size, extra2right) {  
  69.     /* Centers string in a string by padding on right and left 
  70.      * Args: 
  71.      *    str = string to center 
  72.      *    ch = pad character 
  73.      *    size = number of total characters in final string 
  74.      *    extra2right = optional true if extra character should be on right 
  75.      * returns string 
  76.      */  
  77.     var padStr = "";  
  78.     var re;  
  79.     var len = str.length;  
  80.     var rtrnVal;  
  81.   
  82.     if (len <= size) {  
  83.         if (extra2right)  
  84.             re = new RegExp("^(.*)(.{" + len + "})(\\1)");  
  85.         else  
  86.             re = new RegExp("(.*)(.{" + len + "})(\\1)$");  
  87.   
  88.         do {  
  89.             padStr += ch;  
  90.         } while (--size);  
  91.           
  92.         rtrnVal = padStr.replace(re, "$1" + str +"$3");  
  93.     } else {  
  94.         rtrnVal = extractMiddle(str, size, extra2right);  
  95.     }  
  96.     return rtrnVal;  
  97. }//eof padcenter  
  98.   
  99. function centerInStr(inStr, outStr, extra2right) {  
  100.     /* Centers string in a string of same characters 
  101.      * Args: 
  102.      *    inStr = string to center 
  103.      *    outStr = string of same character  
  104.      *    extra2right = optional true if extra character should be on right 
  105.      * returns string 
  106.      */  
  107.     var padStr = "";  
  108.     var re;  
  109.     var len = inStr.length;  
  110.     var size = outStr.length;  
  111.     var rtrnVal;  
  112.   
  113.     if (len <= size) {  
  114.         if (extra2right)  
  115.             re = new RegExp("^(.*)(.{" + len + "})(\\1)");  
  116.         else  
  117.             re = new RegExp("(.*)(.{" + len + "})(\\1)$");  
  118.   
  119.         rtrnVal = outStr.replace(re, "$1" + inStr +"$3");  
  120.     } else {  
  121.         rtrnVal = extractMiddle(inStr, size, extra2right);  
  122.     }  
  123.     return rtrnVal;  
  124. }//eof centerInStr  
  125.   
  126. function centerInStr2(inStr, outStr, extra2right) {  
  127.     /* Centers string in a string of mixed characters replacing characters 
  128.      * Args: 
  129.      *    inStr = string to center within outStr 
  130.      *    outStr = the outer string 
  131.      *    extra2right = optional true if extra character should be on right 
  132.      * returns string 
  133.      */  
  134.     var inSize = inStr.length;  
  135.     var outSize = outStr.length;  
  136.     var l = Math.floor( (outSize - inSize) /2);  
  137.     var re;  
  138.     var rtrnVal;  
  139.   
  140.     if (inSize <= outSize) {  
  141.         if (extra2right)  
  142.             re = new RegExp("(.{"+l+"})(.{" + inSize + "})(.*)");  
  143.         else  
  144.             re = new RegExp("(.*)(.{" + inSize + "})(.{"+l+"})");  
  145.   
  146.         rtrnVal = outStr.replace(re, "$1" + inStr + "$3");  
  147.     } else {  
  148.         rtrnVal = extractMiddle(inStr, outSize, extra2right);  
  149.     }  
  150.   
  151.     return rtrnVal;  
  152. }//eof centerInStr2  
  153.   
  154. function centerInStr3(inStr, outStr, extra2right) {  
  155.     /* Centers string in a mixed string without replacing characters 
  156.      * Args: 
  157.      *    inStr = string to center within outStr 
  158.      *    outStr = the outer string 
  159.      *    extra2right = optional true if extra character should be on right 
  160.      * returns string 
  161.      */  
  162.     var outSize = outStr.length;  
  163.     var inSize = inStr.length;  
  164.     var l = Math.floor(outSize/2);  
  165.     var re;  
  166.     var rtrnVal;  
  167.   
  168.     if (inSize <= outSize) {  
  169.         if (extra2right)  
  170.             re = new RegExp("(.{" + l + "})(.*)");  
  171.         else  
  172.             re = new RegExp("(.*)(.{" + l + "})");  
  173.   
  174.         rtrnVal = outStr.replace(re, "$1" + inStr + "$2");  
  175.     } else {  
  176.         rtrnVal = extractMiddle(inStr, outSize, extra2right);  
  177.     }  
  178.     return rtrnVal;  
  179. }//eof centerStr3  
  180.   
  181. function extractMiddle(str, size, extra2right) {  
  182.     /* Centers string in a string by padding on right and left 
  183.      * Args: 
  184.      *    inStr = string to center within outStr 
  185.      *    outStr = the outer string 
  186.      *    extra2right = optional true if extra character should be on right 
  187.      * returns string 
  188.      */  
  189.     var l = Math.floor( (str.length - size)/2);  
  190.     var re;  
  191.   
  192.     if (extra2right)  
  193.         re = new RegExp("(.{" + l + "})(.{" + size + "})(.*)");  
  194.     else  
  195.         re = new RegExp("(.*)(.{" + size + "})(.{" + l + "})");  
  196.   
  197.     return str.replace(re, "$2");  
  198. }//eof extractMiddle  
  199.   
  200. function back2forward(dataStr){   
  201.     return dataStr.replace(/\\/g, "/");  
  202. }  
  203.   
  204. function forward2back(dataStr) {   
  205.     return dataStr.replace(/\//g, "\\");  
  206. }  
  207.   
  208. function return2br(dataStr) {  
  209.     /* Convert returns in string to html breaks 
  210.      * return string 
  211.      */  
  212.     return dataStr.replace(/(\r\n|[\r\n])/g, "<br />");  
  213. }//eof - return2br  
  214. function return2br2(dataStr) {  
  215.     /* Convert returns in string to html breaks 
  216.      * return string 
  217.      */  
  218.     return dataStr.replace(/(\r\n|\r|\n)/g, "<br />");  
  219. }//eof - return2br2  
  220.   
  221. function cleanString(str) {  
  222.     /* Remove specified characters from string 
  223.      * Arg: str = string to clean 
  224.      * List is left parenthesis, right parenthesis, period, dash, space 
  225.      * Change list inside square brackets [list] 
  226.      * Return string 
  227.      */  
  228.     return str.replace(/[\(\)\.\-\s,]/g, "");  
  229. }//eof - cleanString  
  230.   
  231. function cleanString2(str) {  
  232.     return str.replace(/[^\d]/g, "");  
  233. }  
  234.   
  235. function alpha2numericPhone(phoneStr) {  
  236.     var newStr = phoneStr.replace(/[a-zA-Z]/g, alpha2number);  
  237.     return checkReplaceParm(newStr, "alpha2number");  
  238.   
  239.     function alpha2number(char) {  
  240.         var rtrnVal = null;  
  241.   
  242.         switch (char.toLowerCase()) {  
  243.         case "a"case "b"case "c":  
  244.             rtrnVal = "2";  
  245.             break;  
  246.         case "d"case "e"case "f":  
  247.             rtrnVal = "3";  
  248.             break;  
  249.         case "g"case "h"case "i":  
  250.             rtrnVal = "4";  
  251.             break;  
  252.         case "j"case "k"case "l":  
  253.             rtrnVal = "5";  
  254.             break;  
  255.         case "m"case "n"case "o":  
  256.             rtrnVal = "6";  
  257.             break;  
  258.         case "p"case "q"case "r"case "s":  
  259.             rtrnVal = "7";  
  260.             break;  
  261.         case "t"case "u"case "v":  
  262.             rtrnVal = "8";  
  263.             break;  
  264.         case "w"case "x"case "y"case "z":  
  265.             rtrnVal = "9";  
  266.             break;  
  267.         }  
  268.         return rtrnVal;  
  269.     }  
  270. }  
  271.   
  272. function first_first(name) {  
  273.     return name.replace(/^([^,]*)[,\s]+(\w+)/, "$2 $1");  
  274. }  
  275.   
  276. function last_first (name) {  
  277.     return name.replace(/(.+)\s+([\w']+)$/, "$2, $1"); //'  
  278. }  
  279.   
  280. function switchWords(name) {  
  281.     /* Change order of two words removing optional comma separator 
  282.      * Arg: name = string of two words 
  283.      * Return string no separator 
  284.      */  
  285.     return name.replace(/(\w+),?\s*(\w+)/, "$2 $1");  
  286. }//eof - switchWords  
  287.   
  288. function reversOrder (name) {  
  289.     /* Change order of two words inserting comma separator 
  290.      * Args: name = string of two words 
  291.      * Return string with separator 
  292.      */  
  293.   
  294.     return name.replace(/(\w+),?\s+(\w+)/, "$2, $1");  
  295. }//eof - reversOrder  
  296.   
  297. function cnvrt2upper(str) {  
  298.     /* Convert string to title case capital first letters 
  299.      * Return converted string or original string if not supported 
  300.      */  
  301.     str = alltrim(str);  
  302.     var newStr = str.toLowerCase().replace(/\b[a-z]/g, cnvrt)  
  303.   
  304.     return checkReplaceParm(newStr, "cnvrt");  
  305.   
  306.     function cnvrt() {  
  307.         return arguments[0].toUpperCase();  
  308.     }  
  309. }//eof - cnvrt2upper  
  310.   
  311. function titleCase(str) {  
  312.     str = alltrim(str);  
  313.     var newStr = str.toLowerCase().replace(/\b\w+\b/g, cnvrt);  
  314.     return checkReplaceParm(newStr, "cnvrt");  
  315.   
  316.     function cnvrt() {  
  317.         /*Branch which should be capitalized */  
  318.         if (arguments[arguments.length -2] == 0)  
  319.             /* First word capitalize if first char is letter*/  
  320.             return arguments[0].replace(/^[a-z]/, cnvrt2);  
  321.         else if (/^(a|about|after|an|and|at|by|for|from|in|into|nor|of|on|onto|over|the|to|up|with|within)$/.test(arguments[0]) )  
  322.             /* List of words to skip */  
  323.             return arguments[0];  
  324.         else  
  325.             /* All other capitalize if first character is letter */  
  326.             return arguments[0].replace(/^[a-z]/, cnvrt2);  
  327.     }  
  328.   
  329.     function cnvrt2() {  
  330.         /* Capitalize letter */  
  331.         return arguments[0].toUpperCase();  
  332.     }  
  333. }//eof  
  334. function titleCase2(str) {  
  335.     var re = new RegExp(/^(a|about|after|an|and|at|by|for|from|in|into|nor|of|on|onto|over|the|to|up|with|within)$/);         
  336.   
  337.     return str.toLowerCase().replace(/\b([a-z])(\w*)\b/g, cnvrt);  
  338.   
  339.     function cnvrt() {  
  340.         if (re.test(arguments[0]) && arguments[arguments.length-2])  
  341.             return arguments[0];  
  342.         else  
  343.             return arguments[1].toUpperCase() + arguments[2];  
  344.     }  
  345. }  
  346. function html2entity(str) {  
  347.     /* Convert html <,> to &tl; and &gt; 
  348.      * Agr: str = string that may have html 
  349.      * Return converted string or original string if not supported 
  350.      */  
  351.     var newStr = cnvrt(str);  
  352.     return checkReplaceParm(newStr, "(s)");  
  353.   
  354.     function cnvrt(str){  
  355.         //replace with function  
  356.         return str.replace(/[<>]/g, function (s){ return (s == "<")? "&lt;" :"&gt;"});  
  357.     }  
  358. }//eof - html2entity  
  359.   
  360. function checkReplaceParm(str, fx) {  
  361.     /* Check browser supports functions in replace 
  362.      * No support returns function itself 
  363.      */  
  364.     var re = new RegExp("^\sfunction\s+" + fx);  
  365.     if (re.test(str)) {  
  366.         /* This return can be change to null or 
  367.          * a value of your choice to indicate failure 
  368.          */  
  369.         alert("This browser doesn't support using a function as an argument to the replace method!");  
  370.         return ""  
  371.     }  
  372.     else {  
  373.         return str;  
  374.     }  
  375. }  
  376. /** regexp-parsing-data.js ***/  
  377. function xtractReportType1(data) {  
  378.     /* Approach 1 to extracting data from a string and putting it in another string 
  379.      * Arg: data = source data 
  380.      * Return new string 
  381.      * This fx is of no value accept as a demo. 
  382.      * Watchout for dashes 
  383.      */  
  384.     var array = data.match(/\b[\S]+\b/g);  
  385.     return array[5] + " " + array[0] + " paint retail price: $" + array[2] + " ea.";  
  386. }//eof - xtractReportType1  
  387.   
  388. function xtractReportType2(data){  
  389.     /* Approach 2 to extracting data from a string and putting it in another string 
  390.      * Arg: data = source data 
  391.      * Return new string 
  392.      * This fx is of no value accept as a demo, and not recommended option. 
  393.      */  
  394.     data.match(/^(\S+)\s(\S+)\s(\S+)\s(\S+)\s(\S+)\s(\S+)\b/);  
  395.     return RegExp.$6 + " " + RegExp.$1 + " paint retails for $" + RegExp.$3 + " ea.";  
  396. }//eof - xtractReportType2  
  397.   
  398. function xtractNums(str){  
  399.     /* Create array of numbers in string 
  400.      * Arg: str = source string containing numbers 
  401.      *        can be mixed with words. 
  402.      * Return array of numbers in str 
  403.      * Unlike the previous two, you can use this 
  404.      */  
  405.     return str.match(/\d+/g);  
  406. }//eof - xtractNums  
  407.   
  408. function xtractFormattedNums(data) {  
  409.     /* Create array of numbers in string (including formatted with commas and decimal) 
  410.      * Arg: data = source string containing numbers 
  411.      *        can be mixed with words. 
  412.      * Return array of numbers in str 
  413.      */  
  414.     return data.match(/\d+(,\d{3})*(\.\d{1,2})?/g);  
  415. }//eof - xtractFormattedNums  
  416.   
  417. function parseUrl(url) {  
  418.     /* Parse URL into protocol, host, path, file and hash (and url) 
  419.      *    must be URL only 
  420.      * Args: url 
  421.      * Return object or null if no match 
  422.      */  
  423.   
  424.     url = url.replace(/^\s+|\s+$/g, ''); //alltrim  
  425.   
  426.     if (url.match(/^((http|ftp):\/)?\/?([^:\/\s]+)((\/\w+)*\/)([\w\-\.]+\.[^#?\s]+)(#[\w\-]+)?$/)) {  
  427.         //RegExp['$&'] is null in some browsers s/b original url  
  428.         return  {url: RegExp['$&'], protocol: RegExp.$2,host:RegExp.$3,path:RegExp.$4,file:RegExp.$6,hash:RegExp.$7};  
  429.     }  
  430.     else {  
  431.         return null;  
  432.     }  
  433. }//eof - parseUrl  
  434.   
  435. function parseEmeddedUrl(url) {  
  436.     /* Parse URL into protocol, host, path, file and hash (and url) 
  437.      *        can be embedded in string 
  438.      * Args: url 
  439.      * Return object or null if no match 
  440.      */  
  441.     var e = /((http|ftp):\/)?\/?([^:\/\s]+)((\/\w+)*\/)([\w\-\.]+\.[^#?\s]+)(#[\w\-]+)?/  
  442.     if (url.match(e)) {  
  443.         //RegExp['$&'] is null in some browsers s/b original url  
  444.         return  {url: RegExp['$&'], protocol: RegExp.$2,host:RegExp.$3, path:RegExp.$4,file:RegExp.$6,hash:RegExp.$7};  
  445.     }  
  446.     else {  
  447.         return null;  
  448.     }  
  449. }//eof - parseEmeddedUrl  
  450.   
  451. function xtractFile(data){  
  452.     /* Separate path and filename.ext 
  453.      * Arg: string with path and filename 
  454.      * Return: object 
  455.      */  
  456.     if (data.match(/(.*)\/([^\/\\]+\.\w+)$/)) {  
  457.         return {path: RegExp.$1, file: RegExp.$2};  
  458.     }  
  459.     else {  
  460.         return {path: "", file: ""};  
  461.     }  
  462. }//eof - xtractFile  
  463.   
  464. function xtractFile_sans(data){  
  465.     /* Separate path and filename leaving extention off 
  466.      * Assumes DOS style with only one dot. 
  467.      * Arg: string with path and filename 
  468.      * Return: object 
  469.      */  
  470.     if (data.match(/(.*)\/([^\/\\]+)\.\w+$/)) {  
  471.         return {path: RegExp.$1, file: RegExp.$2};  
  472.     }  
  473.     else {  
  474.         return {path: "", file: ""};  
  475.     }  
  476. }//eof - xtractFile_sans  
  477.   
  478. function xtractFile-ext1(data){  
  479.     /* Parses filename and extension 
  480.      * 
  481.      * Returns Object 
  482.      */  
  483.     data = data.replace(/^\s|\s$/g, "");  
  484.   
  485.     if (/\.\w+$/.test(data)) {  
  486.         var m = data.match(/([^\/\\]+)\.(\w+)$/);  
  487.         if (m)  
  488.             return {filename: m[1], ext: m[2]};  
  489.         else  
  490.             return {filename: "no file name", ext:null};  
  491.     } else {  
  492.         var m = data.match(/([^\/\\]+)$/);  
  493.         if (m)  
  494.             return {filename: m[1], ext: null};  
  495.         else  
  496.             return {filename: "no file name", ext:null};  
  497.     }  
  498. }//eof - xtractFile-ext1  
  499.   
  500. function xtractFile-ext2(data){  
  501.     /* Parses filename and extension 
  502.      * 
  503.      * Returns Object 
  504.      */  
  505.     data = data.replace(/^\s|\s$/g, ""); //trims string  
  506.   
  507.     if (/\.\w+$/.test(data)) }  
  508.         if (data.match(/([^\/\\]+)\.(\w+)$/) )  
  509.             return {filename: RegExp.$1, ext: RegExp.$2};  
  510.         else  
  511.             return {filename: "no file name", ext:null};  
  512.     }  
  513.     else {  
  514.         if (data.match(/([^\/\\]+)$/) )  
  515.             return {filename: RegExp.$1, ext: null};  
  516.         else  
  517.             return {filename: "no file name", ext:null};  
  518.     }  
  519. }//eof - xtractFile-ext2  
  520.   
  521. function xtractFile-ext4type(data){  
  522.     /* Parses filename and extension 
  523.      * for specified extenstions 
  524.      * 
  525.      * Returns Object 
  526.      */  
  527.     data = data.replace(/^\s|\s$/g, ""); //trims string  
  528.   
  529.     if (data.match(/([^\/\\]+)\.(asp|html|htm|shtml|php)$/i) )  
  530.         return {filename: RegExp.$1, ext: RegExp.$2};  
  531.     else  
  532.         return {filename: "invalid file type", ext: null};  
  533. }//eof - xtractFile-ext4type  
  534.   
  535.   
  536. //from http://lawrence.ecorp.net/inet/samples/regexp-format.php 

没有评论:

发表评论