search
HomeWeb Front-endJS Tutorial10 application examples of js regular expressions

10 application examples of js regular expressions

Mar 07, 2018 pm 05:15 PM
javascriptExampleexpression

js中正则表达式的10个应用实例

1、找重复项最多的字符和个数

[html] view plain copy

<script>  
   var str = &#39;sassdfdfffdasdffffffsdsdddsss&#39;;  
   var arr = str.split(&#39;&#39;);//先把字符串分割为字符串数组  
   str = arr.sort().join(&#39;&#39;);对数组进行排序后再将数组转化为字符串  
    var value = &#39;&#39;;  
    var index = 0;  
    var re = /(\w)\1+/g;  
    str.replace(re,function($0,$1){  
       if(index<$0.length){  
          index = $0.length;  
          value = $1;  
       }  
    });  
    alert(&#39;最多的字符:&#39;+ value +&#39; ,重复的次数:&#39;+index);//最多的字符:f ,重复的次数:10  
</script>

2、去掉空格

<script>  
    var str = &#39; hel  lo &#39;  
    function trim(){  
        var re = /^\s+|\s+|\s+$/g;  
        return str.replace(re,&#39;&#39;);  
    }  
    alert(&#39;(&#39;+trim(str)+&#39;)&#39;);//(hello)  
</script>

3、判断是否为邮箱email

验证规则: 电子邮箱的正确写法一般为: 用户名@邮箱网站.com(.cn) 

第一部分:由字母、数字、下划线、短线“-”、点号“.”组成

第二部分:为一个域名,域名由字母、数字、短线“-”、域名后缀组成(域名后缀一般为两位到三位。例如:com cn net现在域名有的也会大于四位)

function isEmail(str){  
       var reg =/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;  
       return reg.test(str);  
   }

4、验证手机号码

验证规则: 11位数字,以1开头

function isEmail(str){  
       var reg =/^1([0-9]){10}$/; //也可以为 <span style="background-color:rgb(255,255,255);">var reg= <span style="color:rgb(0,0,0);font-family:Consolas, &#39;Bitstream Vera Sans Mono&#39;, &#39;Courier New&#39;, Courier, monospace;font-size:14px;text-align:left;white-space:pre;">/^1\d{10}$/;</span></span>  
       return reg.test(str);  
   }

5、验证是否由数字和字母组成

function isEmail(str){  
       var reg =/^([0-9a-zA-Z])+$/;  
       return reg.test(str);  
   }

6、如何获取一个字符串中的数字字符,并按数组形式输出

例如:一串字符串:ddjsd234sdjs45sdda83ndas333sa9382ssd2

var str =&#39;dgfhfgh254bhku289fgdhdy67&#39;;  
    var arr = [];  
    function arrFn(){  
        var re = /\d+/g ;  
        arr.push(str.match(re));  
        return arr;  
    }

7、判断字符串是否存在连续重复的字母

var re = /([a-zA-Z])\1+/;

8、判断是否已元音字母结尾

var re = /[aeiou]$/i;  //不要忘了添加不区分大小写的字符i

9、判断是否符合USD格式

规则:给定字符串 str,检查其是否符合美元书写格式 
1、以 $ 开始 
2、整数部分,从个位起,满 3 个数字用 , 分隔 
3、如果为小数,则小数部分长度为 2 
4、正确的格式如:$1,023,032.03 或者 $2.03,错误的格式如:$3,432,12.12 或者 $34,344.3**

var str =&#39;$1,023,032.03&#39;;  
     var re = /^\$\d{1,3}((,\d{3}))*(\.\d{2})?$/;  //需要注意的是特殊字符要加转义符号\

10、获取URL参数

规则:
1. 指定参数名称,返回该参数的值 或者 空字符串 
2. 不指定参数名称,返回全部的参数对象 或者 {} 
3. 如果存在多个同名参数,则返回数组**

//    获取 url 参数  
    function getUrlParam(sUrl, sKey) {  
        var arr={};  
        sUrl.replace(/\??(\w+)=(\w+)&?/g,function(match,p1,p2){  
            //console.log(match,p1,p2);  
            if(!arr[p1]){  
                arr[p1]=p2;  
            }  
            else {  
                var p=arr[p1];  
                arr[p1]=[].concat(p,p2);  
            }  
  
        })  
        if(!sKey)return arr;  
        else{  
            for(var ele in arr){  
                if(ele==sKey){return arr[ele];}  
            }  
            return "";  
        }  
    }

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

相关阅读:

Spring的配置

Spring的MVC配置

Hibernate的映射文件详解

The above is the detailed content of 10 application examples of js regular expressions. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Java vs JavaScript: A Detailed Comparison for DevelopersJava vs JavaScript: A Detailed Comparison for DevelopersMay 16, 2025 am 12:01 AM

JavaandJavaScriptaredistinctlanguages:Javaisusedforenterpriseandmobileapps,whileJavaScriptisforinteractivewebpages.1)Javaiscompiled,staticallytyped,andrunsonJVM.2)JavaScriptisinterpreted,dynamicallytyped,andrunsinbrowsersorNode.js.3)JavausesOOPwithcl

Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool