Basic knowledge about javascript Regular Expressions

Source: Internet
Author: User

Basic knowledge about javascript Regular Expressions

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:

?

1

2

3

4

5

6

7

8

9

10

11

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:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

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); // connects adjacent numbers.

}

Else {// execute this command whenever the connected number is disconnected.

If (temp ){

Arr. push (temp );

Temp = '';

}

};

}

If (temp) {// The purpose here is to display the last number, for which I do not want to explain

Arr. push (temp );

Temp = '';

}

Return arr;

};

Then we use a regular expression to solve the functions implemented by this function:

?

1

2

3

4

5

6

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:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

<! 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); // connects adjacent numbers.

}

Else {// execute this command whenever the connected number is disconnected.

If (temp ){

Arr. push (temp );

Temp = '';

}

};

}

If (temp) {// The purpose here is to display the last number, for which I do not want to explain

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>

From the above example, we can see 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 generated to process strings more efficiently. They are the same as string processing methods, but more efficient and concise (regular expressions can only process strings)

Next, let's take a look at some common Regular Expressions:

Before that, let's talk about the regular expression. Regular Expressions are the same as other objects, such as array (), object (), and Date (). They all have initialization methods.

Var re =/the Matching content should be written here. If not written, it means watching the symbol/; // This is the simple creation of the regular object, I will use it directly in subsequent articles.

Var re = new RegExp (); // This creation method is also acceptable. You know, but what is different from simple writing is that parameter passing is a bit different.

(1) test

Meaning: regular expressions are used to match strings. If the matching succeeds, true is returned. Otherwise, false is returned;

Syntax: re. test (string );

Let's start with the escape character:

/S space/S non-space/d Number/D Non-number/w characters (letters, numbers, underscores)/W non-characters

For example, judge whether a string is a number.

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

<! DOCTYPE>

<Html>

<Head>

<Meta charset = 'utf-8'>

<Title> </title>

</Head>

<Script type = "text/javascript">

Window. onload = function (){

Var str = 'dgh6a567sdo23ujaloo932 ';

Var str2 = '20140901 ';

Function allNumber (obj ){

Var re =/\ D/; // define a regular object to match non-numeric values. If there is a non-numeric value, the result is returned after the match ends.

If (re. test (obj )){

Alert ('all numbers ');

}

Else {

Alert ('all numbers ');

};

};

AllNumber (str );

AllNumber (str2 );

 

};

</Script>

<Body>

</Body>

</Html>

(2) search

Meaning: regular expressions are used to match strings. If a match is successful, the return value is-1. The return value is the same as the indexof () function 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 id I. [/color]

In this example, a character in a case-insensitive deregularizedstring is matched.

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

<! 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; // defines that the regular object matches B characters, not case sensitive

Alert (obj. search (re ));

};

SearchStr (str );

};

</Script>

<Body>

</Body>

</Html>

(3) match

Meaning: regular expressions are used to match strings. If a match is successful, an array with a successful match is returned. Otherwise, Null is returned.

Syntax: String. match (re );

[Color = Red] Note: In regular expressions, the corresponding value is returned immediately after a successful match, and the matching will not continue. If you want to search for all, you need to add g (Global match) [/color]

Example: match consecutive numbers in a string and store them in an array (continuous numbers are used as an item of the array)

The "+" in the program appears at least once. Why?

We mentioned earlier that "the regular expression returns the corresponding value immediately after the matching is successful by default", and the result ends when a number is matched in the string, returns a number to an array. In this case, we need to use g to match each element.

Whether consecutive numbers are not determined or not, "+" can be used to satisfy the number of dynamic numbers.

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

<! 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/g; // two-digit global match

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: regular expressions are used to match strings. When a successfully matched string is replaced by a new string

Syntax: String. replace (re );

Example: replace all a in the string with B.

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

<! 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; // global match

Return obj. replace (re, 'B ');

};

Console. log (replaceStr (str ));

};

</Script>

<Body>

</Body>

</Html>

It will be written here for the time being to follow up with the new...

The above is all the content of this article. I hope you will like it.

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.