正则表达式【JavaScript版】

A)用正则表达式代替常规的字符串处理

     用处一:探测子串在原串中的位置(数组下标从0开始)

  
    
1 var SourceString = " first string for detecting,second string for Detecting " ;
2 var RegExpObject = / detecting / ; // 等价于: RegExpObject=new RegExp("detecting")
3 alert( " 探测到的子串'detecting'在原串中的位置为: " + SourceString.search(RegExpObject)); // 等价于:SourceString.indexOf("detecting")
   

     用处二:获取子串在原串中的个数

  
    
1 var SourceString = " first string for detecting,second string for Detecting " ;
2 var RegRegExpObjectGlobal = / detecting / gi; // 等价于:RegRegExpObjectGlobal=new RegExp("detecting","gi")
3 // i 保证大写的Detecting也能被探测到
4 var MatchStringArr = SourceString.match(RegRegExpObjectGlobal);
5 alert( " 全局探测到的返回数组长度为: " + MatchStringArr.length + " , 第一个元素为: " + MatchStringArr[ 0 ] + " , 第二个元素为: " + MatchStringArr[ 1 ]);

     用处三:字符串替换

  
    
1 var ColorString = " first color is red,second color is red ,third color is red " ;
2 var RegExpRed = / red / ;
3 alert( " 单个替换后的字符串为: " + ColorString.replace(RegExpRed, " yellow " )); // 等价于:ColorString.replace("red","yellow")
4 var RegExpRedGlobal = / red / gi;
5 alert( " 全局替换后的字符串为: " + ColorString.replace(RegExpRedGlobal, " yellow " ));

     用处四:字符串分割

  
    
1 var WeekDayString = " Monday,Tuesday,Wednesday " ;
2 var RegExpChar = / \, / ;
3 var WeekDayArr = WeekDayString.split(RegExpChar); // 等价于:WeekDayString.split(",")
4 alert( " 分割后的字符串数组长度为: " + WeekDayArr.length + " ,第一个元素为: " + WeekDayArr[ 0 ] + " ,第二个元素为: " + WeekDayArr[ 1 ] + " ,第三个元素为: " + WeekDayArr[ 2 ]);

B)实用专题

   专题一:判断整个字符串是否由若干位纯数字组成

  
    
1 var NumberString = " 123456789 " ;
2 var RegExpNumber = / (\d){9} / ;
3 var isNineNumbers = ((RegExpNumber.test(NumberString)) && NumberString.length == 9 );
4 alert( " 判断是否是9位数字: " + isNineNumbers);

  专题二:在javascript中就将首尾的空格去掉   (注:javaScript本身没有trim方法)

   
     
1 var StringWithSpace = " this is a demo for selfdefined trim function " ;
2 alert( " 原字符串为:' " + StringWithSpace + " ' " );
3 var RegExpSpace = / ^\s*(.*?)\s+$ / ;
4 var DestinateString = StringWithSpace.replace(RegExpSpace, " $1 " );
5 alert( " 转换后的字符串为:' " + DestinateString + " ' " );

   详细可参考:http://blog.csdn.net/wujian6636/archive/2007/06/06/1640215.aspx

你可能感兴趣的:(JavaScript)