Teach you to easily handle the regular in JavaScript

Tell me Zhan to hide 2020-11-06 20:37:32
teach easily handle regular javascript



1 Overview of regular expressions

1.1 What is regular expression

Regular expressions (Regular Expression) Is a pattern used to match character combinations in strings . stay Javascript in , Regular expressions are also objects .
Regular tables are usually used to retrieve , Replace those that match a pattern ( The rules ) The text of , For example, validation forms : Only English letters can be entered in the user name form 、 Numbers or underscores , Enter your nickname in Chinese ( matching ). Besides , Regular expressions are also often used to filter out sensitive words in the content of a page , Or get the specific part we need from the string ( extract ) etc. .

1.2 Regular expression features

  1. flexibility 、 Very logical and functional
  2. You can quickly achieve complex control of strings in extremely simple ways
  3. It's hard to understand

2 The regular expression is in Javascript The use of

2.1 Create regular expression

  1. adopt RegExp Object's constructor creation
var Variable name = new RegExp(/ expression /)
// utilize RegExp Create objects 
var regexp = new RegExp(/123/)
console.log(regexp)
  1. Create... By literals
var Variable name = / expression /
var rg = /123/
console.log(rg)

2.2 Test regular expressions test

test() Regular object methods , Used to detect whether a string conforms to this rule , The object will return true or false, Its parameter is the test string .

regexObj.test(str)
  • regexObj It's a regular expression written
  • str The text we're going to test
  • It's testing str Whether the text conforms to our regular expression specification
var rg = /123/
console.log(rg.test(123)) //true
console.log(rg.test('abc')) //false 

3 Special characters in regular expressions

3.1 The composition of regular expressions

A regular expression can be made up of simple characters , such as /abc/, It can also be a combination of simple and special characters , such as /ab*c/. Special characters are also called metacharacters , In regular expressions, they are special symbols with special meanings .
Because there are many special characters , I'm not going to list them here , You can refer to :
MDN:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Regular_Expressions
Here we can divide metacharacters into several types of learning :

3.2 Border character

Boundary characters in regular expressions ( Position symbol ) Used to indicate the position of a character , There are mainly two characters .
image.png
If ^ and $ At the same time , Then the exact match is achieved

var rg= /abc/ // There's no need for quotation marks in regular expressions 
// /abc/ As long as it contains abc This string returns true
console.log(rg.test('abc')) // true
console.log(rg.test('abcd')) // true
console.log(rg.test('aabcd')) // true
var reg = /^abc/
console.log(rg.test('abc')) // true
console.log(rg.test('abcd')) // true
console.log(rg.test('aabcd')) // false
var reg = /^abc$/ // Exactly match , The requirement must be abc Only strings conform to the specification 
console.log(rg.test('abc')) // true
console.log(rg.test('abcd')) // false
console.log(rg.test('aabcd')) // false
console.log(rg.test('abcabc')) // false

3.3 Character class

Indicates that there is a series of characters to choose from , Just match one of them , All available characters are enclosed in square brackets

var rg = /[abc]/; // As long as it contains a perhaps b perhaps c All back to true
console.log(rg.test('andy')) //true
var rg = /[abc]/; // As long as it contains a perhaps b perhaps c All back to true
console.log(rg.test('baby')) //true
console.log(rg.test('color')) //true
console.log(rg.test('red')) //false
var rg = /^[abc]$/ // Choose one of three Only a Or is it b Or is it c, These three letters return to true
console.log(rg.test('aa')) //false
console.log(rg.test('a')) //true
console.log(rg.test('b')) //true
console.log(rg.test('c')) //true
console.log(rg.test('abc')) //false
var rg = /^[a-z]$/ //26 English letters, any letter returns true
var rg = /^[a-zA-Z]$/ //26 English letters ( Upper case and lower case ) Any letter returns true
var rg = /^[a-zA-Z0-9_-]$/
console.log(rg.test('c')) //true
console.log(rg.test('B')) //true
console.log(rg.test('_')) //true
console.log(rg.test('8')) //true
console.log(rg.test('-')) //true
// If there is ^, It means to take the opposite , To match the border ^ Don't confuse 
var rg = /^[^a-zA-Z]$/

3.4 Quantifier sign

Quantifier is used to set the number of times a pattern appears
image.png

var reg = /^a*$/
console.log(reg.test(''))// true
console.log(reg.test('a'))// true
console.log(reg.test('aaa'))// true
var reg = /^a+$/
console.log(reg.test(''))// false
console.log(reg.test('a'))// true
console.log(reg.test('aaa'))// true
var reg = /^a?$/
console.log(reg.test(''))// true
console.log(reg.test('a'))// true
console.log(reg.test('aaa'))// false
var reg = /^a{3}$/
console.log(reg.test(''))// false
console.log(reg.test('a'))// false
console.log(reg.test('aaa'))// true
var reg = /^a{3,}$/
console.log(reg.test(''))// false
console.log(reg.test('a'))// false
console.log(reg.test('aaa'))// true
console.log(reg.test('aaaaa'))// true
var reg = /^a{
3,5}$/ //{3,5} Don't leave a space after a comma 
console.log(reg.test(''))// false
console.log(reg.test('a'))// false
console.log(reg.test('aaa'))// true
console.log(reg.test('aaaaa'))// true

User name verification

  1. If the user name is legal , Then the following prompt message is : The user name is legal , And the color is green
  2. If the user name is not legal , Then the following prompt message is : The user name does not conform to the specification , And the color is green

User name authentication analysis :

  1. The user name can only be in English letters , Numbers , An underline or dash , And the length of the user name is 6~16 position .
  2. First prepare this regular expression pattern
  3. If it's a regular specification , Let's have the following span add right class .
  4. If it doesn't conform to the regular specification , Let's have the following span add wrong class .
<input type="text" class="uname"> <span> Please enter a user name </span>
<style> span {  color: #aaa; font-size: 14px; } .right {  color: green; } .wrong {  color: red; } </style>
var reg=/^[a-zA-Z0-9-_]{6,16}$/
var uname = doucument.querySelector('.uname');
var spn = doucument.querySelector('span');
uname.onblur = function() {

if(res.test(this.value)){

span.className='right'
span.innerHTML = ' The user name input format is correct '
} else {

span.className='wrong'
span.innerHTML = ' User name input format error '
}
}

3.5 Brackets summarize

  1. Curly braces : Quantifier sign It means the number of repetitions
  2. brackets : Character set . Match any character in the formula bracket
  3. parentheses : Express priority
// brackets 
var reg = /^[abc]$/ //a||b||c
// Curly braces 
var reg = /^abc{
3}$/ // It just makes c Repeat three times 
// parentheses 
var reg = /^(abc){
3}$/ //abc Repeat three times 

3.6 Predefined classes

Predefined class refers to the abbreviation of some common patterns
image.png

Landline number verification

var reg= /^\d{
3}-\d{
8}|\d{
4}-\d{
7}$/ // | It means or means 
var reg= /^\d{3,4}-\d{7,8}|\d{4}-\d{7}$/

4 Substitution in regular expressions

4.1 replace Replace

replace() Method can implement the replacement string operation , The replacement parameter can be a string or a regular expression .

stringObject.replace(regxp/substr, replacement)
  1. The first parameter : Replaced string or regular expression
  2. The second parameter : Replace with a string of
  3. The return value is a new string after replacement
var str = 'lanfeng and qianduan'
var newStr = str.replace('front', 'qianduan')
console.log(newstr)

Message filtering sensitive words

<textarea name="" id="message"></textarea> <button> Submit </button>
var text = document.querySelector('textarea');
var btn = document.querySelector('button');
var div = doucment.querySelector('div');
btn.onclick = function () {

div.innerHTML = text.value.replace(/ passion /g, '**')
}

4.2 Regular expression parameters

/ expression /[switch]

switch( Also known as a modifier ) According to what pattern to match , There are three values

  • g: The global matching
  • i: Ignore case
  • gi: The global matching + Ignore case

summary

This article mainly shares javascript Some knowledge points and usage of middle regular .

版权声明
本文为[Tell me Zhan to hide]所创,转载请带上原文链接,感谢

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云