Home Web Front-end JS Tutorial Introduction to the basics of javascript regular expressions_javascript skills

Introduction to the basics of javascript regular expressions_javascript skills

May 16, 2016 pm 04:03 PM
javascript regular expression Regular expression basics

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"]
Copy after login

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;
  };
Copy after login

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;
  };
Copy after login

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>
Copy after login

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>

Copy after login

(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>
Copy after login

(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>

Copy after login

(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>
Copy after login

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.

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Can PowerPoint run JavaScript? Can PowerPoint run JavaScript? Apr 01, 2025 pm 05:17 PM

JavaScript can be run in PowerPoint, and can be implemented by calling external JavaScript files or embedding HTML files through VBA. 1. To use VBA to call JavaScript files, you need to enable macros and have VBA programming knowledge. 2. Embed HTML files containing JavaScript, which are simple and easy to use but are subject to security restrictions. Advantages include extended functions and flexibility, while disadvantages involve security, compatibility and complexity. In practice, attention should be paid to security, compatibility, performance and user experience.

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

See all articles