`
caniggia1986
  • 浏览: 151432 次
  • 性别: 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

分享到:
评论

相关推荐

    javascript正则表达式综合练习

    总结来说,JavaScript正则表达式是一个强大的文本处理工具,通过理解和熟练运用上述知识点,开发者可以有效地处理字符串操作,进行数据验证,以及在各种场景下实现复杂的数据匹配。`validator.js`文件可以作为实践...

    javascript正则表达式学习笔记

    这篇学习笔记将深入探讨JavaScript正则表达式的概念、语法和实际应用。 一、正则表达式基础 1. 创建正则表达式: - 字面量表示法:`/pattern/flags` - 构造函数:`new RegExp('pattern', 'flags')` 2. 常见的...

    JavaScript正则表达式迷你书(1.1版)_程序逻辑_

    **JavaScript正则表达式迷你书(1.1版)** 正则表达式是JavaScript中一个强大的工具,用于处理文本字符串,进行模式匹配和查找、替换等操作。它们在编程逻辑中扮演着至关重要的角色,尤其是在处理字符串数据时,...

    常用Javascript正则表达式汇总

    以下是一些常见的JavaScript正则表达式及其应用: 1. **匹配中文字符**:`[\u4e00-\u9fa5]` 这个正则表达式用于匹配Unicode范围内的中文字符,包括所有汉字。例如,如果你想在一个字符串中查找所有中文字符,可以...

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

    总之,JavaScript的正则表达式和递归函数是强大的工具,它们在数据验证、字符串处理和复杂逻辑实现等方面发挥着重要作用。了解并熟练掌握这些技术,能显著提高编写高效、健壮的JavaScript代码的能力。

    使用正则表达式验证一年的12个月份

    在实际应用中,通常会结合编程语言来使用这些正则表达式。例如,在JavaScript中,你可以用`test()`函数来验证输入: ```javascript const regex = /^(0?[1-9]|1[0-2])$/; // 或者更复杂的版本 const input = "05"; ...

    jS 正则表达式实现关键字高亮显示

    在JS中,正则表达式是通过构造函数`RegExp`创建的,或者使用正则字面量`/pattern/flags`。它们用来定义模式,以匹配特定的字符串序列。例如,匹配所有数字的正则表达式是`/\d+/`。 2. **关键词匹配** 要实现...

    javascript正则表达式表单验证大全

    以下是从标题、描述、标签以及部分内容中提取的关键知识点,详细解释了如何使用JavaScript正则表达式进行各种常见场景下的表单验证。 #### 用户名验证 正则表达式:`^[a-zA-Z][\w]{5,17}$` 该表达式确保用户名由...

    JavaScript正则表达式使用详解.zip

    文件"JavaScript正则表达式使用详解.txt"很可能包含了关于这些概念的详细解释和实例,而"NCIE书上的例子.txt"可能是某个教程书籍中的练习案例,这些资源可以帮助深入理解并掌握JavaScript正则表达式。 文件"P179_1....

    Javascript正则表达式测试网页.rar

    JavaScript正则表达式是网页开发中的重要工具,用于处理文本数据的验证、查找、替换等操作。在网页制作过程中,熟练掌握正则表达式能够极大地提高代码效率和灵活性。本压缩包“Javascript正则表达式测试网页.rar”...

    JavaScript正则表达式工具

    JavaScript正则表达式工具是一种基于JavaScript开发的应用程序,旨在帮助开发者和编程爱好者更方便地理解和使用正则表达式。在编程领域,正则表达式(Regular Expression)是一种强大的文本处理工具,广泛应用于字符...

    三目运算符+正则表达式

    三目运算符和正则表达式结合使用时,可以实现更高效的代码。比如,在一个输入验证功能中,我们可以用三目运算符判断用户输入是否为空,然后根据结果使用正则表达式进行进一步的验证: ```javascript let input = ...

    JavaScript正则表达式迷你书(1.1版)

    在1.1版的《JavaScript正则表达式迷你书》中,作者深入浅出地介绍了这一强大功能的使用方法。 正则表达式,或称regex,是一种特殊的字符序列,它能帮助我们高效地查找、替换和提取符合特定规则的文本。在JavaScript...

    javascript正则表达式详解

    综上所述,JavaScript正则表达式是一门深奥但实用的技术,涵盖了许多概念和技巧。通过不断学习和实践,你可以更好地利用正则表达式解决各种文本处理问题,成为JavaScript编程的高手。对于初学者来说,这个...

    正则表达式调试工具

    综上所述,"正则表达式调试工具V3.0 绿色免费版"是一款实用的开发辅助工具,不仅提供了基本的正则表达式测试功能,还通过经典例程和跨平台特性,为开发者提供了便利的学习和调试环境。使用这款工具,开发者可以更好...

    Javascript正则表达式

    ### JavaScript中的正则表达式详解 #### 一、正则表达式基础概念 正则表达式(Regular Expression),...通过掌握这些基础知识和实践案例,你可以更深入地了解如何在JavaScript中有效使用正则表达式进行字符串处理。

Global site tag (gtag.js) - Google Analytics