


Introduction to the basics of javascript regular expressions_javascript skills
What are the benefits of regular expressions? Let’s first understand:
We use the method of processing strings in js to write a function to extract the numbers in the string:
var str='dgh6a567sdo23ujaloo932'; function getNumber(obj){ var arr=[]; for (var i = 0; i < obj.length; i++) { if (obj.charAt(i)>='0'&&obj.charAt(i)<='9'){ arr.push(obj.charAt(i)); } } return arr; }; console.log(getNumber(str)); //["6", "5", "6", "7", "2", "3", "9", "3", "2"]
We took out the numbers in the string with the above method, but we are not satisfied. What we need is the form ['6','567','23','932'], and transform the function:
function getNumber(obj){ var arr=[]; var temp=''; for (var i = 0; i < obj.length; i++) { if (obj.charAt(i)>='0'&&obj.charAt(i)<='9'){ temp+=obj.charAt(i);//现将相邻的数字连接起来 } else{ //每当连接的数字断开时,就在这执行 if (temp) { arr.push(temp); temp=''; } }; } if (temp) { //这里的作用是为了显示最后数字的,原因不想解释 arr.push(temp); temp=''; } return arr; };
Then we use regular expressions to solve the functions implemented by this function:
function getNumber2(obj){ var arr=[]; var re=/\d+/g; arr.push(obj.match(re)); return arr; };
Let’s take a complete look at the running results of the program:
<!DOCTYPE> <html> <head> <meta charset='utf-8'> <title></title> </head> <script type="text/javascript"> window.onload=function(){ var str='dgh6a567sdo23ujaloo932'; /*function getNumber(obj){ var arr=[]; for (var i = 0; i < obj.length; i++) { if (obj.charAt(i)>='0'&&obj.charAt(i)<='9'){ arr.push(obj.charAt(i)); } } return arr; };*/ function getNumber(obj){ var arr=[]; var temp=''; for (var i = 0; i < obj.length; i++) { if (obj.charAt(i)>='0'&&obj.charAt(i)<='9'){ temp+=obj.charAt(i);//现将相邻的数字连接起来 } else{ //每当连接的数字断开时,就在这执行 if (temp) { arr.push(temp); temp=''; } }; } if (temp) { //这里的作用是为了显示最后数字的,原因不想解释 arr.push(temp); temp=''; } return arr; }; function getNumber2(obj){ var arr=[]; var re=/\d+/g; arr.push(obj.match(re)); return arr; }; console.log(getNumber(str)); console.log(getNumber2(str)); }; </script> <body> </body> </html>
We can see from the above example that the regular expression method has the same effect, but the code is shorter and more efficient. This is the benefit of regular expressions
Regular expressions are created to process strings more efficiently. They are the same as string processing methods, but more efficient and concise (regular expressions can only process strings)
Let’s systematically study some common methods of regularization:
Before this, let’s talk about how to write regular expressions. Regular expressions are the same as other objects array(), object(), Date(), etc., and they all have initialization methods
var re=/You need to write matching things here. If you don’t write it, you will just focus on the symbol/; //This is a simple creation of a regular object. I will use it directly in the following articles
var re=new RegExp(); //This way of creation is also possible, everyone knows, but the difference from the abbreviation is that the parameter passing is a little different
(1)test
Meaning: Regularly match strings, return true when the match is successful, otherwise, return false;
Syntax: re.test(string);
Let’s talk about escape characters first:
/s space /S non-space /d number /D non-number /w character (letter, number, underscore) /W non-character
For example: Determine whether a string is all numbers
<!DOCTYPE> <html> <head> <meta charset='utf-8'> <title></title> </head> <script type="text/javascript"> window.onload=function(){ var str='dgh6a567sdo23ujaloo932'; var str2='123456'; function allNumber(obj){ var re=/\D/;//定义正则对象匹配非数字,只要有不是数字的就是匹配结束返回结果 if (re.test(obj)) { alert('不全是数字'); } else{ alert('全是数字'); }; }; allNumber(str); allNumber(str2); }; </script> <body> </body> </html>
(2) search
Meaning: Regularly match strings. When the match is successful, the position of the successful match is returned. Otherwise, -1 is returned; the same function as indexof() in the string processing method
Syntax: string.search(re);
[color=Red]Note: The regular expression is case-sensitive by default. To make it case-insensitive, add the i flag;[/color]
Example, case-insensitive regular matching of a certain character
in a string
<!DOCTYPE> <html> <head> <meta charset='utf-8'> <title></title> </head> <script type="text/javascript"> window.onload=function(){ var str='dgh6b567sdo23ujaloo932'; function searchStr(obj){ var re=/B/i;//定义正则对象匹配b字符,不区分大小写 alert(obj.search(re)); }; searchStr(str); }; </script> <body> </body> </html>
(3) match
Meaning: Regularly match strings. When the match is successful, an array of successful matches will be returned. Otherwise, Null
will be returned.
Syntax: string.match(re);
[color=Red] Note: The default in the regular expression is that as long as the match is successful, it will immediately end and return the corresponding value, and the match will not continue. If you want to find them all, you need to add g (global matching) [/color]
Example: Match consecutive numbers in a string and store them in an array (the consecutive numbers are used as an item in the array)
The " " in the program means that the match occurs at least once. Why do we do this?
We mentioned earlier that "the default in regular expressions is that as long as the match is successful, it will end immediately and return the corresponding value." Then it will end when a number is matched in the string, and a number will be returned to the array. At this time, what we need is to use g to make it match every element.
Have you ever discovered that there is no definite number of consecutive numbers? You can use " " to meet the dynamic number of numbers.
<!DOCTYPE> <html> <head> <meta charset='utf-8'> <title></title> </head> <script type="text/javascript"> window.onload=function(){ var str='dgh6b567sdo23ujaloo932'; function searchStr1(obj){ var re=/\d/; return obj.match(re); }; function searchStr2(obj){ var re=/\d/g; return obj.match(re); }; function searchStr3(obj){ var re=/\d\d/g;//全局匹配2位数 return obj.match(re); }; function searchStr4(obj){ var re=/\d+/g; return obj.match(re); }; console.log(searchStr1(str)); console.log(searchStr2(str)); console.log(searchStr3(str)); console.log(searchStr4(str)); }; </script> <body> </body> </html>
(4)replace
Meaning: Regularly match strings, and when the successfully matched string is replaced by a new string
Syntax: string.replace(re);
Example: Replace all a’s in the string with b
<!DOCTYPE> <html> <head> <meta charset='utf-8'> <title></title> </head> <script type="text/javascript"> window.onload=function(){ var str='daah6b5a7sdo23ujaloo932'; function replaceStr(obj){ var re=/a/g; //全局匹配a return obj.replace(re,'b'); }; console.log(replaceStr(str)); }; </script> <body> </body> </html>
I will write here for the time being and follow up with updates. . .
The above is the entire content of this article, I hope you all like it.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver CS6
Visual web development tools