- //去除字符串空格
- /*** Start of Modify ***/
- function ltrim(str){
- /* Trims leading spaces - returns string
- * Returns trimmed string
- */
- return str.replace(/^\s+/, '');
- }//eof - ltrim
- function rtrim(str) {
- /* Trims trailing spaces - returns string
- * Returns trimmed string
- */
- return str.replace(/\s+$/, '');
- }//eof - rtrim
- function alltrim(str) {
- /* Trims leading and trailing spaces
- * Returns trimmed string
- */
- return str.replace(/^\s+|\s+$/g, '');
- }//eof - alltrim
- //填充
- function padleft(str, ch, num) {
- /* Pads string on left with number characters
- * Args:
- * str = string to pad
- * ch = pad character
- * num = number of total characters in final string
- * returns string
- */
- ch = ch || " "; //otherwise pad.length remains 0.
- //Create pad string num chars
- var pad = "";
- do {
- pad += ch;
- } while(pad.length < num);
- //Regular express take num chars from right
- var re = new RegExp(".{" + num + "}$")[0];
- return re.exec(pad + str);
- }//eof - padleft
- function padright(str, ch, num){
- /* Pads string on right with number characters
- * Args:
- * str = string to pad
- * ch = pad character
- * num = number of total characters in final string
- * returns string
- */
- ch = ch || " "; //otherwise pad.length remains 0.
- //Create pad string num chars
- var pad = "";
- do {
- pad += ch;
- } while (pad.length < num);
- //Regular express take num chars from left
- var re = new RegExp("^.{" + num + "}");
- return re.exec(str + pad)[0];
- }//eof - padright
- function padcenter(str, ch, size, extra2right) {
- /* Centers string in a string by padding on right and left
- * Args:
- * str = string to center
- * ch = pad character
- * size = number of total characters in final string
- * extra2right = optional true if extra character should be on right
- * returns string
- */
- var padStr = "";
- var re;
- var len = str.length;
- var rtrnVal;
- if (len <= size) {
- if (extra2right)
- re = new RegExp("^(.*)(.{" + len + "})(\\1)");
- else
- re = new RegExp("(.*)(.{" + len + "})(\\1)$");
- do {
- padStr += ch;
- } while (--size);
- rtrnVal = padStr.replace(re, "$1" + str +"$3");
- } else {
- rtrnVal = extractMiddle(str, size, extra2right);
- }
- return rtrnVal;
- }//eof padcenter
- function centerInStr(inStr, outStr, extra2right) {
- /* Centers string in a string of same characters
- * Args:
- * inStr = string to center
- * outStr = string of same character
- * extra2right = optional true if extra character should be on right
- * returns string
- */
- var padStr = "";
- var re;
- var len = inStr.length;
- var size = outStr.length;
- var rtrnVal;
- if (len <= size) {
- if (extra2right)
- re = new RegExp("^(.*)(.{" + len + "})(\\1)");
- else
- re = new RegExp("(.*)(.{" + len + "})(\\1)$");
- rtrnVal = outStr.replace(re, "$1" + inStr +"$3");
- } else {
- rtrnVal = extractMiddle(inStr, size, extra2right);
- }
- return rtrnVal;
- }//eof centerInStr
- function centerInStr2(inStr, outStr, extra2right) {
- /* Centers string in a string of mixed characters replacing characters
- * Args:
- * inStr = string to center within outStr
- * outStr = the outer string
- * extra2right = optional true if extra character should be on right
- * returns string
- */
- var inSize = inStr.length;
- var outSize = outStr.length;
- var l = Math.floor( (outSize - inSize) /2);
- var re;
- var rtrnVal;
- if (inSize <= outSize) {
- if (extra2right)
- re = new RegExp("(.{"+l+"})(.{" + inSize + "})(.*)");
- else
- re = new RegExp("(.*)(.{" + inSize + "})(.{"+l+"})");
- rtrnVal = outStr.replace(re, "$1" + inStr + "$3");
- } else {
- rtrnVal = extractMiddle(inStr, outSize, extra2right);
- }
- return rtrnVal;
- }//eof centerInStr2
- function centerInStr3(inStr, outStr, extra2right) {
- /* Centers string in a mixed string without replacing characters
- * Args:
- * inStr = string to center within outStr
- * outStr = the outer string
- * extra2right = optional true if extra character should be on right
- * returns string
- */
- var outSize = outStr.length;
- var inSize = inStr.length;
- var l = Math.floor(outSize/2);
- var re;
- var rtrnVal;
- if (inSize <= outSize) {
- if (extra2right)
- re = new RegExp("(.{" + l + "})(.*)");
- else
- re = new RegExp("(.*)(.{" + l + "})");
- rtrnVal = outStr.replace(re, "$1" + inStr + "$2");
- } else {
- rtrnVal = extractMiddle(inStr, outSize, extra2right);
- }
- return rtrnVal;
- }//eof centerStr3
- function extractMiddle(str, size, extra2right) {
- /* Centers string in a string by padding on right and left
- * Args:
- * inStr = string to center within outStr
- * outStr = the outer string
- * extra2right = optional true if extra character should be on right
- * returns string
- */
- var l = Math.floor( (str.length - size)/2);
- var re;
- if (extra2right)
- re = new RegExp("(.{" + l + "})(.{" + size + "})(.*)");
- else
- re = new RegExp("(.*)(.{" + size + "})(.{" + l + "})");
- return str.replace(re, "$2");
- }//eof extractMiddle
- function back2forward(dataStr){
- return dataStr.replace(/\\/g, "/");
- }
- function forward2back(dataStr) {
- return dataStr.replace(/\//g, "\\");
- }
- function return2br(dataStr) {
- /* Convert returns in string to html breaks
- * return string
- */
- return dataStr.replace(/(\r\n|[\r\n])/g, "<br />");
- }//eof - return2br
- function return2br2(dataStr) {
- /* Convert returns in string to html breaks
- * return string
- */
- return dataStr.replace(/(\r\n|\r|\n)/g, "<br />");
- }//eof - return2br2
- function cleanString(str) {
- /* Remove specified characters from string
- * Arg: str = string to clean
- * List is left parenthesis, right parenthesis, period, dash, space
- * Change list inside square brackets [list]
- * Return string
- */
- return str.replace(/[\(\)\.\-\s,]/g, "");
- }//eof - cleanString
- function cleanString2(str) {
- return str.replace(/[^\d]/g, "");
- }
- function alpha2numericPhone(phoneStr) {
- var newStr = phoneStr.replace(/[a-zA-Z]/g, alpha2number);
- return checkReplaceParm(newStr, "alpha2number");
- function alpha2number(char) {
- var rtrnVal = null;
- switch (char.toLowerCase()) {
- case "a": case "b": case "c":
- rtrnVal = "2";
- break;
- case "d": case "e": case "f":
- rtrnVal = "3";
- break;
- case "g": case "h": case "i":
- rtrnVal = "4";
- break;
- case "j": case "k": case "l":
- rtrnVal = "5";
- break;
- case "m": case "n": case "o":
- rtrnVal = "6";
- break;
- case "p": case "q": case "r": case "s":
- rtrnVal = "7";
- break;
- case "t": case "u": case "v":
- rtrnVal = "8";
- break;
- case "w": case "x": case "y": case "z":
- rtrnVal = "9";
- break;
- }
- return rtrnVal;
- }
- }
- function first_first(name) {
- return name.replace(/^([^,]*)[,\s]+(\w+)/, "$2 $1");
- }
- function last_first (name) {
- return name.replace(/(.+)\s+([\w']+)$/, "$2, $1"); //'
- }
- function switchWords(name) {
- /* Change order of two words removing optional comma separator
- * Arg: name = string of two words
- * Return string no separator
- */
- return name.replace(/(\w+),?\s*(\w+)/, "$2 $1");
- }//eof - switchWords
- function reversOrder (name) {
- /* Change order of two words inserting comma separator
- * Args: name = string of two words
- * Return string with separator
- */
- return name.replace(/(\w+),?\s+(\w+)/, "$2, $1");
- }//eof - reversOrder
- function cnvrt2upper(str) {
- /* Convert string to title case capital first letters
- * Return converted string or original string if not supported
- */
- str = alltrim(str);
- var newStr = str.toLowerCase().replace(/\b[a-z]/g, cnvrt)
- return checkReplaceParm(newStr, "cnvrt");
- function cnvrt() {
- return arguments[0].toUpperCase();
- }
- }//eof - cnvrt2upper
- function titleCase(str) {
- str = alltrim(str);
- var newStr = str.toLowerCase().replace(/\b\w+\b/g, cnvrt);
- return checkReplaceParm(newStr, "cnvrt");
- function cnvrt() {
- /*Branch which should be capitalized */
- if (arguments[arguments.length -2] == 0)
- /* First word capitalize if first char is letter*/
- return arguments[0].replace(/^[a-z]/, cnvrt2);
- 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]) )
- /* List of words to skip */
- return arguments[0];
- else
- /* All other capitalize if first character is letter */
- return arguments[0].replace(/^[a-z]/, cnvrt2);
- }
- function cnvrt2() {
- /* Capitalize letter */
- return arguments[0].toUpperCase();
- }
- }//eof
- function titleCase2(str) {
- 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)$/);
- return str.toLowerCase().replace(/\b([a-z])(\w*)\b/g, cnvrt);
- function cnvrt() {
- if (re.test(arguments[0]) && arguments[arguments.length-2])
- return arguments[0];
- else
- return arguments[1].toUpperCase() + arguments[2];
- }
- }
- function html2entity(str) {
- /* Convert html <,> to &tl; and >
- * Agr: str = string that may have html
- * Return converted string or original string if not supported
- */
- var newStr = cnvrt(str);
- return checkReplaceParm(newStr, "(s)");
- function cnvrt(str){
- //replace with function
- return str.replace(/[<>]/g, function (s){ return (s == "<")? "<" :">"});
- }
- }//eof - html2entity
- function checkReplaceParm(str, fx) {
- /* Check browser supports functions in replace
- * No support returns function itself
- */
- var re = new RegExp("^\sfunction\s+" + fx);
- if (re.test(str)) {
- /* This return can be change to null or
- * a value of your choice to indicate failure
- */
- alert("This browser doesn't support using a function as an argument to the replace method!");
- return ""
- }
- else {
- return str;
- }
- }
- /** regexp-parsing-data.js ***/
- function xtractReportType1(data) {
- /* Approach 1 to extracting data from a string and putting it in another string
- * Arg: data = source data
- * Return new string
- * This fx is of no value accept as a demo.
- * Watchout for dashes
- */
- var array = data.match(/\b[\S]+\b/g);
- return array[5] + " " + array[0] + " paint retail price: $" + array[2] + " ea.";
- }//eof - xtractReportType1
- function xtractReportType2(data){
- /* Approach 2 to extracting data from a string and putting it in another string
- * Arg: data = source data
- * Return new string
- * This fx is of no value accept as a demo, and not recommended option.
- */
- data.match(/^(\S+)\s(\S+)\s(\S+)\s(\S+)\s(\S+)\s(\S+)\b/);
- return RegExp.$6 + " " + RegExp.$1 + " paint retails for $" + RegExp.$3 + " ea.";
- }//eof - xtractReportType2
- function xtractNums(str){
- /* Create array of numbers in string
- * Arg: str = source string containing numbers
- * can be mixed with words.
- * Return array of numbers in str
- * Unlike the previous two, you can use this
- */
- return str.match(/\d+/g);
- }//eof - xtractNums
- function xtractFormattedNums(data) {
- /* Create array of numbers in string (including formatted with commas and decimal)
- * Arg: data = source string containing numbers
- * can be mixed with words.
- * Return array of numbers in str
- */
- return data.match(/\d+(,\d{3})*(\.\d{1,2})?/g);
- }//eof - xtractFormattedNums
- function parseUrl(url) {
- /* Parse URL into protocol, host, path, file and hash (and url)
- * must be URL only
- * Args: url
- * Return object or null if no match
- */
- url = url.replace(/^\s+|\s+$/g, ''); //alltrim
- if (url.match(/^((http|ftp):\/)?\/?([^:\/\s]+)((\/\w+)*\/)([\w\-\.]+\.[^#?\s]+)(#[\w\-]+)?$/)) {
- //RegExp['$&'] is null in some browsers s/b original url
- return {url: RegExp['$&'], protocol: RegExp.$2,host:RegExp.$3,path:RegExp.$4,file:RegExp.$6,hash:RegExp.$7};
- }
- else {
- return null;
- }
- }//eof - parseUrl
- function parseEmeddedUrl(url) {
- /* Parse URL into protocol, host, path, file and hash (and url)
- * can be embedded in string
- * Args: url
- * Return object or null if no match
- */
- var e = /((http|ftp):\/)?\/?([^:\/\s]+)((\/\w+)*\/)([\w\-\.]+\.[^#?\s]+)(#[\w\-]+)?/
- if (url.match(e)) {
- //RegExp['$&'] is null in some browsers s/b original url
- return {url: RegExp['$&'], protocol: RegExp.$2,host:RegExp.$3, path:RegExp.$4,file:RegExp.$6,hash:RegExp.$7};
- }
- else {
- return null;
- }
- }//eof - parseEmeddedUrl
- function xtractFile(data){
- /* Separate path and filename.ext
- * Arg: string with path and filename
- * Return: object
- */
- if (data.match(/(.*)\/([^\/\\]+\.\w+)$/)) {
- return {path: RegExp.$1, file: RegExp.$2};
- }
- else {
- return {path: "", file: ""};
- }
- }//eof - xtractFile
- function xtractFile_sans(data){
- /* Separate path and filename leaving extention off
- * Assumes DOS style with only one dot.
- * Arg: string with path and filename
- * Return: object
- */
- if (data.match(/(.*)\/([^\/\\]+)\.\w+$/)) {
- return {path: RegExp.$1, file: RegExp.$2};
- }
- else {
- return {path: "", file: ""};
- }
- }//eof - xtractFile_sans
- function xtractFile-ext1(data){
- /* Parses filename and extension
- *
- * Returns Object
- */
- data = data.replace(/^\s|\s$/g, "");
- if (/\.\w+$/.test(data)) {
- var m = data.match(/([^\/\\]+)\.(\w+)$/);
- if (m)
- return {filename: m[1], ext: m[2]};
- else
- return {filename: "no file name", ext:null};
- } else {
- var m = data.match(/([^\/\\]+)$/);
- if (m)
- return {filename: m[1], ext: null};
- else
- return {filename: "no file name", ext:null};
- }
- }//eof - xtractFile-ext1
- function xtractFile-ext2(data){
- /* Parses filename and extension
- *
- * Returns Object
- */
- data = data.replace(/^\s|\s$/g, ""); //trims string
- if (/\.\w+$/.test(data)) }
- if (data.match(/([^\/\\]+)\.(\w+)$/) )
- return {filename: RegExp.$1, ext: RegExp.$2};
- else
- return {filename: "no file name", ext:null};
- }
- else {
- if (data.match(/([^\/\\]+)$/) )
- return {filename: RegExp.$1, ext: null};
- else
- return {filename: "no file name", ext:null};
- }
- }//eof - xtractFile-ext2
- function xtractFile-ext4type(data){
- /* Parses filename and extension
- * for specified extenstions
- *
- * Returns Object
- */
- data = data.replace(/^\s|\s$/g, ""); //trims string
- if (data.match(/([^\/\\]+)\.(asp|html|htm|shtml|php)$/i) )
- return {filename: RegExp.$1, ext: RegExp.$2};
- else
- return {filename: "invalid file type", ext: null};
- }//eof - xtractFile-ext4type
- //from http://lawrence.ecorp.net/inet/samples/regexp-format.php
2012年3月11日星期日
使用JavaScript正则表达式实现一些实用函数
订阅:
博文评论 (Atom)
没有评论:
发表评论