`
caniggia1986
  • 浏览: 149634 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

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

阅读更多
//去除字符串空格
/*** 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 &gt;
     * 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 == "<")? "&lt;" :"&gt;"});
    }
}//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

分享到:
评论

相关推荐

    使用正则表达式的模式匹配

    ECMAScript v3对JavaScript正则表达式进行了标准化。JavaScript 1.2实现了ECMAScript v3要求的正则表达式特性的子集,JavaScript 1.5实现了完整的标准。JavaScript的正则表达式完全以Perl程序设计语言的正则表达式...

    JavaScript正则表达式校验与递归函数实际应用实例解析.docx

    JavaScript正则表达式校验与递归函数实际应用实例解析.docx

    javascript正则表达式函数用法详解

    javascript正则表达式函数用法详解

    javascript 正则表达式.doc

    JavaScript的RegExp对象和String对象定义了使用正则表达式来执行强大的模式匹配和文本检索与替换函数的方法. 在JavaScript中,正则表达式是由一个RegExp对象表示的.当然,可以使用一个RegExp()构造函数来创建RegExp...

    正则表达式单行、多行模式简介(使用说明)

    目前常用正则表达式都有该使用选项,如:javascript 正则表达式,一般是:”/正则表达式匹配字符/修饰符“ ,最后一个”/” 后面是修饰符。然后,php也是类似的,c#,python等,一般调用正则表达式的匹配函数,都有...

    JavaScript正则表达式

    JavaScript正则表达式 一、认识正则表达式 1、正则表达式是描述字符模式的对象,正则表达式用于对字符串模式匹配及检索替换,是对字符串执行模式匹配的强大工具。 2、String和RegExp都定义了使用正则表达式进行强大...

    JS正则表达式大全.docx

    在JavaScript中,正则表达式是由一个RegExp对象表示的.当然,可以使用一个RegExp()构造函数来创建RegExp对象, 也可以用JavaScript 1.2中的新添加的一个特殊语法来创建RegExp对象.就像字符串直接量被定义为包含在引号...

    javascript中正则表达式及匿名函数相结合的典型应用实例

    javascript中正则表达式及匿名函数相结合的...通过一个小例子详细说明和介绍了在javascript中如何应用正则表达式,以及在什么时候下可以应用匿名函数。 并介绍了如何将这两种结合在一起。 实例代码简洁清晰,值得参考。

    JavaScript正则表达式函数总结(常用)

    正则表达式作为一种匹配处理字符串的利器在很多语言中都得到了广泛实现和应用.这篇文章主要介绍了JavaScript正则表达式函数总结,需要的朋友可以参考下

    JavaScript 正则表达式 ajax

    JavaScript概述ajax课件函数,控制语句,正则表达式

    JavaScript正则表达式校验与递归函数实际应用实例解析

    JS递归函数(菲波那切数列) 实例解析:  一组数字:0 1 1 2 3 5 8 13 0 1 2 3 4 5 6 7  sl(0)=0;  sl(1)=1;  sl(2)=sl(0)+sl(1);... 正则表达式检验 //校验是否全由数字组成 function isDigit(s) { va

    PHP正则表达式基本语法和使用方法

    正则表达式(regular expression)是一种表示方式,最早在LINUX被当做一种搜索算法应用在编辑器中,后来被广泛应用,不仅PHP脚本支持正则表达式,Perl、C#、Java以及JavaScript和MySQL也对正则表达式支持。...

    js正则表达式常用函数详解

    一、js正则表达式之replace函数用法...本模块涉及的内容包括字符串创建,正则表达式隐式创建对象,创建正则表达式,进行replace方法的使用匹配 示例代码: &lt;html&gt; [removed] //要替换的字符串的内容 var objS

    IP 正则表达式验证

    javascript 手机号码正则表达式验证函数JS正则表达式验证数字代码JavaScript正则表达式验证身份证号码是否合法(两种方法)jquery正则表达式验证(手机号、身份证号、中文名称)邮箱地址正则表达式验证代码合集软件...

    正则表达式经典实例

    3.2 导入正则表达式函数库 3.3 创建正则表达式对象 3.4 设置正则表达式选项 3.5 检查是否可以在目标字符串中找到匹配 3.6 检查正则表达式能否整个匹配目标字符串 3.7 获取匹配文本 3.8 决定匹配的位置和长度 ...

    正则表达式经典实例.pdf

    3.2 导入正则表达式函数库 3.3 创建正则表达式对象 3.4 设置正则表达式选项 3.5 检查是否可以在目标字符串中找到匹配 3.6 检查正则表达式能否整个匹配目标字符串 3.7 获取匹配文本 3.8 决定匹配的位置和长度 3.9 ...

    正则表达式

    JavaScript的RegExp对象和String对象定义了使用正则表达式来执行强大的模式匹配和文本检索与替换函数的方法. 在JavaScript中,正则表达式是由一个RegExp对象表示的.当然,可以使用一个RegExp()构造函数来创建RegExp...

    JavaScript正则表达式验证代码(推荐)

    可以使用正则表达式来描述要检索的内容。 简单的模式可以是一个单独的字符。更复杂的模式包括了更多的字符,并可用于解析、格式检查、替换等等。 //判断输入内容是否为空 function IsNull(){ var str = document....

    javascript的正则表达式

    正则表达式就是专门为了校验数据而产生的一个语法,除了可以校验数据,还可以提取一些想要的固定模式数据,还可以替换数据 – 替换字符串(正则表达式主要用于字符串的处理 ) 正则表达式就是一个模式,可以用来校验...

Global site tag (gtag.js) - Google Analytics