Basic knowledge about javascript Regular Expressions _ javascript skills

Source: Internet
Author: User
I haven't looked at regular expressions for a long time. It happened to be used today. I have a new record here and I will share some basic knowledge with you, the focus is on the four common methods in regular expressions, and the originality in 50% of the exercises. Where are the benefits of regular expressions? Let's take a look at the following:
We use the string processing method in js to write the function to retrieve 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"]

In the above method, we retrieve the numbers in the string, but we are not satisfied. What we need is in the form of ['6', '123', '23', '123, transform functions:

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); // connect adjacent numbers} else {// execute if (temp) {arr. push (temp); temp = '';}};} if (temp) {// The role here is to display the last number. The reason is not to explain arr. push (temp); temp = '';} return arr ;};

Then we use a regular expression 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 full look at the running results of the program:

  
   

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.