search
HomeWeb Front-endJS TutorialRegular questions you will encounter in interviews

正则表达式,有木有人像我一样,学了不知道多少遍,学的时候看起来都懂了,过一段时间就又忘的差不多了,等真正要用到的时候,还是一脸懵逼。说到底还是练习的不够多,一直处于只看不做的程度上。所以搜集了这些正则习题,来保证温故而知新。建议读者看完题目后可以自己先做一做,然后再看实现方法。本文不讲基础,只记录习题,如果后续有新的题目,也会保持更新。

1、var s1 = "get-element-by-id";     给定这样一个连字符串,写一个function转换为驼峰命名法形式的字符串  getElementById

var f = function(s) {
    return s.replace(/-\w/g, function(x) {
        return x.slice(1).toUpperCase();
    })
}

2、判断字符串是否包含数字

function containsNumber(str) {
    var regx = /\d/;
    return regx.text(str);
}

3、判断电话号码

function isPhone(tel) {
    var regx = /^1[34578]\d{9}$/;
    return regx.test(tel);
}

4、判断是否符合指定格式

给定字符串str,检查其是否符合如下格式

  1. XXX-XXX-XXXX

  2. 其中X为Number类型

function matchesPattern(str) {
    return /^(\d{3}-){2}\d{4}&/.test(str);
}

5、判断是否符合USD格式

给定字符串 str,检查其是否符合美元书写格式

  1. 以 $ 开始

  2. 整数部分,从个位起,满 3 个数字用 , 分隔

  3. 如果为小数,则小数部分长度为 2

  4. 正确的格式如:$1,023,032.03 或者 $2.03,错误的格式如:$3,432,12.12 或者 $34,344.3**

function isUSD(str) {
    var regx = /^\$\d{1,3}(,\d{3})*(\.\d{2})?$/;
    return regx.test(str);
}

6、JS实现千位分隔符

function format(number) {
    var regx = /\d{1,3}(?=(\d{3})+$)/g;
    return (number + '').replace(regx, '$&,')  // $&表示与regx相匹配的字符串
}

7、获取 url 参数

获取 url 中的参数

  1. 指定参数名称,返回该参数的值 或者 空字符串

  2. 不指定参数名称,返回全部的参数对象 或者 {}

  3. 如果存在多个同名参数,则返回数组

function getUrlParam(url, key) {
    var arr = {};
    url.replace(/\??(\w+)=(\w+)&?/g, function(match, matchKey, matchValue) {
       if (!arr[matchKey]) {
           arr[matchKey] = matchValue;
       } else {
           var temp = arr[matchKey];
           arr[matchKey] = [].concat(temp, matchValue);
       }
    });
    if (!key) {
        return arr;
    } else {
        for (ele in arr) {
            if (ele = key) {
                return arr[ele];
            }
        }
        return '';
    }
}

8、验证邮箱

function isEmail(email) {
    var regx = /^([a-zA-Z0-9_\-])+@([a-zA-Z0-9_\-])+(\.[a-zA-Z0-9_\-])+$/;
    return regx.test(email);
}

9、验证身份证号码

身份证号码可能为15位或18位,15位为全数字,18位中前17位为数字,最后一位为数字或者X

function isCardNo(number) {
    var regx = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
    return regx.test(number);
}

10、匹配汉字

var regx = /^[\u4e00-\u9fa5]{0,}$/;

11、去除首尾的'/'

var str = '/asdf//';
str = str.replace(/^\/*|\/*$/g, '');

12、判断日期格式是否符合 '2017-05-11'的形式,简单判断,只判断格式

var regx = /^\d{4}\-\d{1,2}\-\d{1,2}$/

13、判断日期格式是否符合 '2017-05-11'的形式,严格判断(比较复杂)

var regx = /^(?:(?!0000)[0-9]{4}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)-02-29)$/;

14、IPv4地址正则

var regx = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;

15、十六进制颜色正则

var regx = /^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/;

16、车牌号正则

var regx = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/;

17、过滤HTML标签

var str="<p>dasdsa</p>nice <br> test"
var regx = /]+>/g;
str = str.replace(regx, '');

18、密码强度正则,最少6位,包括至少1个大写字母,1个小写字母,1个数字,1个特殊字符

var regx = /^.*(?=.{6,})(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*? ]).*$/;

19、URL正则

var regx = /^((https?|ftp|file):\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/;

20、匹配浮点数

var regx = /^-?([1-9]\d*\.\d*|0\.\d*[1-9]\d*|0?\.0+|0)$/;

21、

写一个正则表达式,匹配 "

var str = '<option>待处理</option>';
var regx = /^<.>/;
var resiult = regx.exec(str)[0];</.>

最后推荐一个练习正则的网站 regulex%7B2%7D%5Cd%7B4%7D%26),可以查看正则匹配的走向

如果喜欢请关注我的Github,给个Star吧,我会定期分享一些JS中的知识,^_^

相关推荐:

五道典型的javascript面试题

The above is the detailed content of Regular questions you will encounter in interviews. 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
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.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

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 Article

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)