JS Classic Regular Expression pen question summary _javascript skill

Source: Internet
Author: User

This article summarizes the JS Classic regular expression of the pen test. Share to everyone for your reference, specific as follows:

I. Review the traditional operation of strings

How to get a numeric character in a string and output it as an array, as

Dgfhfgh254bhku289fgdhdy675gfh

Output [254,289,675]

Analysis: Loop The Charat () method to get each substring, to determine whether he is between 0~9, is to throw him into the prepared array

var str= "DGFHFGH254BHKU289FGDHDY675GFH";
FindNum (str);
function FindNum () {
 var arr=[];
 for (Var i=0;i<str.length;i++) {
  if (Str.charat (i) <= ' 9 ' &&str.charat (i) >= ' 0 ') {
   Arr.push ( Str.charat (i));
   Alert (arr);}}}


But this will output [2,5,4,2,8,9,6,7,5] and the result we want is a bit biased, so we need a new empty string, every time we run into a number to go if, touch the character go else, go else, and then store those numbers in the new empty string, Then add it to the array by push, and then empty the string so that you can store it again next time

var str= "dgfhfgh254bhku289fgdhdy675";
FindNum (str);
function FindNum () {
 var arr=[];
 var result= "";
 for (Var i=0;i<str.length;i++) {
  if (Str.charat (i) <= ' 9 ' &&str.charat (i) >= ' 0 ') {
   result+= Str.charat (i);  Note Add the direction do not reverse the
  }
  else{
   if (result) {
    Arr.push (result);
    Result= "";
 }}} Alert (arr)
}

There is also a hidden danger: If the end of the end with a number, then will not enter else, the last few digits will not read, so the For loop outside add again else inside the IF loop

Two. What is a regular, what is the use

Regular: Also known as rules, allowing computers to read human rules

* Where is the front end used?

such as registration page to enter the user name, we give a set of rules to determine whether he entered the right

Range

is used to manipulate strings (that is, don't use them to manipulate objects or anything).

* How to write?

is also a system object, like array, JSON, there is also a rule of writing

abbreviated VAR re=//; Write only two slashes, the browser will think it is a comment, so try not to give him a blank, notice between the two slashes do not have quotes

Full name var re=new RegExp (); Reg is a regular shorthand, exp is shorthand for an expression

For the most part, there is only one case in which the full name is written: the time when a reference is required

Note: When the full name is used, you need two \ or the escape character

Three. Common methods of regular expressions

1.test

Regular to match the string, if the match succeeds returns true, the match fails to return false

Wording: Regular. Test (String)

Such as:

var str= ' abcdef ';
var re=/b/; BC a whole also in the string, pop-up true, but write BD, pop-up false, because there is no BD in the string of such a whole
alert (re.test (str));

Eject True

Extended:

Detects whether a string is full of digits

var str= ' 8621t56461 ';
var re=//;
if (Re.test (str)) {
 alert ("Not all digits");
}
else{
 alert ("All Numbers");
}

What to write between the two slashes? Introducing Escape characters

\s (\s): spaces (not spaces)

\d (\d): Digital (not digital)

\w (\w): Character (non-character) characters include letters, numbers, underscores

2.search

To match the string, if the match succeeds, return the position where the match succeeded, and return-1 if the match fails

Search: String. Search (Regular)

Such as:

var str= "abcdef";
var re=/b/;
Alert (Str.search (re));
Return 1
var re=/w/;
Return-1
var re=/b/;
Return-1

Default in Regular: case-sensitive

If you are not case-sensitive, Mark I at the end of the regular

var re=/b/i

Complete writing:

var re=new RegExp ("B", "I");

3.match

Regular to match the string, if the match succeeds, return the array that matches the success, if the match is unsuccessful, return null

Match's style: string. Match (Regular)

Like the example above, to figure out

var str= "dgfhfgh254bhku289fgdhdy675";
var re=/\d/;
Alert (Str.match (re));
Output 2

Why don't you find the back?

Regular default: Regular match success will end and will not continue to match

If you want to find all, you need to label G (Global Match)

var re=/\d/g;
Output 2,5,4,2,8,9,6,7,5

And we want the result is still biased, if you want to be connected to find, rather than separate, you need

var re=/\d\d/g; Two two for
var re=/\d\d\d/g;//Three Three for

But the number is not necessarily how to find, the introduction of quantifiers

Quantifiers: Matching an indeterminate location

+: appear at least once

var re=/\d+/g;

To achieve the above effect.

4.replace

Regular to match the string, match the successful character to replace the new string

Replace: string. Replace (regular, new string)

Such as:

var str= "AAA";
var re=/a/;
Str=str.replace (Re, "B");
alert (str);
Output BAA

Filtering examples of sensitive words

Str.replace (Re, "*");

But if there are a lot of words to filter, can't write a whole paragraph, so that not match, how to separate a word a word?

|: or Meaning

New question: All sensitive words will be replaced by a star, how to do a few words a few stars?

The second parameter of replace (), which can be a string, can be a callback function

Str.replace (Re,function () {return
 ' * ';
});

Now, it's the same thing as the above sentence.

The first parameter of the callback function is the match of the successful character, that is, the length of the first argument can be used to return a few stars to him

Str.replace (Re,function (str) {
 var result= ';
 for (Var i=0;i<str.length;i++) {
  result+= ' * ';
 }
 return result;
});

Four. Regular expression character class

Character class: A group of similar elements (represented by [] the whole of a character, () is the meaning of the grouping and the subkeys)

1. Any character

[ABC]

such as O[USB]T--OBT, OST, out

2. Scope

[A-z], [0-9]

such as ID[0-9]--ID0, ID5

3. Excluding

[^a]

such as O[^0-9]t--oat, O?t, O t

Example: Filter Labels

Filter out <> (e.g. <div>, </div>,

var re=/<[\w\w]+>/g; The relationship between the brackets, which is either a character or a non character, includes a slash, quotes, etc.

Another approach: Var re=/<[^>]+>/g;

Five. Regular expression escape character

. (point): any character \.: The real point

\s (\s): spaces (not spaces)

\d (\d): Digital (not digital)

\w (\w): Character (non-character) characters include letters, numbers, underscores

\ Number: Duplicate subkey (\1: The first subkey that repeats, \ 2: The second subkey that repeats ...)

var str= "ABCA";
var re=/(a) (b) (c) \1/; True, why not use Var re=/(a) (b) (c) \a/; match success, \ Number, for indeterminate subkey characters
var re=/(a) (b) (c) \2///false
alert (re.teat (str)) ;

Example: Find the most frequently occurring character in a string and how many times it appears

var str= "vbbbbhybbfhbbgbbb";
var arr=str.split ("");
Str=arr.sort (). Join ("");
var value= ""; Store the most occurrence of the characters
var index=0//Storage times
var re=/(\w) \1+/g;

No \1,re is a whole sequence of strings, with \1 is the occurrence of repeated removal to like this bbb...,hh

Str.replace (Re,function ($0,$1) {//$0 represents the whole and represents the first subkey
 if (Index<$0.length) {//$0: Each group of duplicated elements
  index=$0.length ;
  Value=$1
 }
})
Alert (' The most frequent character is ' +value+ ', the number of occurrences is ' +index ');

\b (\b): A separate part (beginning, end, space) of an independent part (a part that is not independent)

Such as:

var str= "Onetwo";
var re=/\bone/; The starting position, True
var re=/one\b///false, to True,one and two with a space or only one
alert (re.test (str));

Examples of the application of independent parts

It is useful to use encapsulated functions to get classname

function Getbyclass (oparent,sclass) {
 var aele=oparent.getelementsbytagname ("*");
 var aresult=[];
 var i;
 for (i=0;i<aele.length;i++) {
  if (aele[i].classname==sclass) {
   aresult.push (aele[i]);
  }
 return aresult;
};

This is going to be a bug.

<div class= "Box1" ></div>
<div class= "Box1box2" ></div>
<div class= "Box1 box2" ></div>

Using this method to get box1, you can only get the first

Rewrite with regular

function Getbyclass (oparent,sclass) {
 var aele=oparent.getelementsbytagname ("*");
 var aresult=[];
 var i;
 var re=new RegExp (' \\b ' +sclass+ ' \\b ') for
 (i=0;i<aele.length;i++) {
  if (re.test (Aele[i].classname)) {
   Aresult.push (Aele[i]);
  }
 return aresult;
};

Six. quantifier

Indeterminate Number of characters

Quantifiers: {}

{4,7} appears at least 4 times, up to 7 times

{4,} appears at least 4 times

{4} occurs just 4 times

+ is shorthand for {}, equivalent to (1,)

? Equal to {0,1}//appearing 0 or 1 times

* equal to {0,}//At least 0 times, can not

Seven. Regular closure

^: The initial position of the regular, indicating the meaning of the beginning

$: The last of the regular, meaning of the end

Example: Remove the space in the string

var re=/^\s+|\s+$/g;
Str.replace (Re, "");

Example: Detection mailbox

var re=/^\w+@[a-z0-9]+ (\.[ a-z]+) {1,3}$/;

Eight. Forward declaration and Counter-forward declaration

(? =): Forward declaration

(?!): Anti-forward declaration

Example

var str= "Abacad";
var re=/a (? =b)/g;
Str=str.replace (Re, "*");
alert (str);

Output: *bacad

If instead

var re=/a (?!) b)/g;

Output: Ab*c*d

PS: Here again for you to provide 2 very convenient regular expression tools for your reference to use:

JavaScript Regular expression online test tool:
Http://tools.jb51.net/regex/javascript

Regular expression online generation tool:
Http://tools.jb51.net/regex/create_reg

More readers interested in JavaScript-related content can view this site: "JavaScript Regular expression Skills encyclopedia", "javascript replacement Operation Tips Summary", "JavaScript Search Algorithm Skills summary", " JavaScript data structure and algorithm skills summary, JavaScript traversal algorithm and tips summary, JavaScript JSON operation tips Summary, javascript error and debugging skills summary and JavaScript mathematical calculation of usage summary 》

I hope this article will help you with JavaScript programming.

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.