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

WBOY
Release: 2016-05-16 16:03:01
Original
1365 people have browsed it

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.

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template