This is the first day of my participation in the August Challenge. For details, see:August is more challenging

Consolidate the basic knowledge of learning javascript, deepen the understanding of memory, to build a solid foundation to build a tall building, come on!!

15 common JS regular expressions, such as the user name and password

Common sense:

  • Regular by/ /The parcel
  • point.Represents one arbitrary character,^The beginning,$Indicates the end.
  • Check if the string looks like this: a 4-bit word./ ^... $/
  • []List what is allowed by this digit:
  • in[-]The medium short bar indicates an interval range, namely “to” :
    • [a-z]Lowercase letters are allowed
    • [0-9]The number is allowed and is equivalent to \d
  • with{}Said digits
    • {2, 7}Say only2 ~ 7position
    • {0, 1}Is equivalent to?The question mark indicates yesZero or one.
    • , {0}Is equivalent to*, model indicates yesZero or more.
  • Use a backslash to “disambiguate” and escape the character.

Learn a few special notations:

  • \dThat’s all the numbers, that’s the same thing as[0-9]
  • \wRepresents all letters, digits, and underscores, equivalent to[a-zA-Z0-9_]
  • \sRepresents all Spaces
  • \bWord boundaries
  • \BNon-word boundary
  • gAccording to the global
  • iCase insensitive

Capture in re

str.replace(/^\s*(.*?) [\s\n]*$/g, ‘$1’) The material in that

// This can be optimized as:
str.replace(/^\s+(.*?) \s+$/g.'$1')

// Or use:
str.replace(/^\s+|\s+$/g."")
Copy the code

The test method

Syntax: regex.test (string)

The re does not write the beginning and end, which means to check whether there is a 4-bit part. Not just these four.

capture

Match the grammar

Syntax: string.match(regular)

The string can be dotted around to call the match method, which means we’re looking for something to match, with parentheses. Parentheses are the capture symbol.

"A, I love you, B, m, m, c".match(/^a(.+)b(.+)c$/)

// [" I love you ", "I love you "," I love you ", "I love you "," I love you ", "I love you "," I love you ", "I love you "," I love you ", "index: 0, input:" I love you ", "groups: undefined]
Copy the code

The result is an array, the 0th item is a string, the first item is captured by the first parenthesis, the second item is captured by the second parenthesis, and so on… .

The exec method

Syntax: regular. Exec (string)

If you do it the other way around, it’s regular. Strings need to be exec, and the result is the same.

/^a(.+)b(.+)c$/.exec("A, I love you, B, m, m, c")

// [" I love you ", "I love you "," I love you ", "I love you "," I love you ", "I love you "," I love you ", "I love you "," I love you ", "index: 0, input:" I love you ", "groups: undefined]
Copy the code

The replace method

Syntax: string.replace(reg,’ replace ‘)

'I like badminton, and badminton likes to sleep'.replace(/ badminton /g.'Table tennis');
// "I like table tennis, and table tennis likes to sleep"

'abcdefeer'.replace(/e/gi.'do things');
/ / "abcd fostered fostered fostered f r"
Copy the code

The /g modifier is global.

I means case insensitive.

The search method

Search is an advanced version of Indexof, and you can use regex. Returns the index of the matching character

'Goose, goose, goose, goose, goose, ha ha ha'.search(/ ha. + /)
/ / 6
Copy the code

🌰 chestnuts

  1. Please convert the dollar amount in the following paragraph into RMB at the exchange rate of 6.8.
// I am so happy. I bought an iphoneX for 678 dollars and a mouse for 36 dollars. I am 10 centimeters taller.

const str2 = "So happy, I bought an iphoneX for $678, and a mouse for $36.70, and I grew 10 cm, so happy.";

var ss = str.replace(/(\d+(\.\d+)?) Usd/g , function(str , $1){
    return $1 * 6.8 + "Yuan"
});

console.log(ss);
Copy the code
  1. Implement the template engine. Give you a template:

{{xinqing}} I bought {{dongxi}} and spent {{qian}} yuan on {{xinqing}}!”

var template = "Good {{xinqing}}! I bought {{dongxi}} and spent {{qian}} yuan on {{xinqing}}!";

var dictionary = {
xinqing: "Happy".dongxi: "Mobile phone".qian: 800
}

var str = template.replace(/\{\{(\w+)\}\}/g , function(str , $1){
return dictionary[$1];
});

console.log(str); // How happy I am! I bought a mobile phone, spent 800 yuan, really happy ah!
Copy the code

  1. Extract from web addresses/index/news/gudianTo refinenews.
console.log("/index/news/gudian".match(/\/index\/(\w+)\/(\w+)/) [1]); 
// news 
console.log("/index/news/gudian".match(/\/index\/(\w+)\/(\w+)/) [2]); 
// gudian
Copy the code
  1. Extract the text in the tag
var str = 

Please pick me

; console.log( str.match(+ \ [^ \ / \ < >] > ([^ \] +) \ < / \ [^ \ >] + \ > /) [1]) // please pick me Copy the code
  1. Remove HTML tags
var str = 

Please pick me

; console.log(str.replace(/<[^<>]+>/g.' ')) // "Hello, please pick me up" Copy the code
  1. Add a guizheng method to the string that removes the first and last Spaces.
String.prototype.guizheng = function(){
    return this.replace(/^\s+(.+?) \s+$/g.function(str , $1){
        return $1; })}console.log(" asdfadsfasdf ".guizheng() + "Ahhh, ahhh, ahhh.");
// asdfadsfasdf
Copy the code

? You can put the capture into “non-greed mode”.

  1. Add thousandths to the string “23423453454365456” to “23,423,453,454,365,456”

Find a non-word boundary that ends with one or more sets of three numbers. “23424324324234234”.replace(/\B(? =(\d{3})+ )/g,”,”); (? =)/g , “,”); (? = )/g,”,”); (? =) is called a positional clause, also known as a reverse lookup, and describes what happens at the end.


Commonly used 🌰 chestnuts

  1. Verify the user name and password (” ^ [a zA – Z] \ w {5, 15} $”) the correct format: “[a-z] [a-z] _ [0-9]”, and the first word must be a letter 6 ~ 16.
  2. Verify phone number: (“^(\d{3,4}-)\d{7,8}$”) correct format: XXX /xxxx-xxxxxxx/ XXXXXXXX;
  3. Check mobile phone number: “^ 1 [3 4 5 | | | 8] [0-9] \ d {8} $”;
  4. To verify the ID number (15 or 18 digits) : “\d{17}[[0-9], 0-9xx]”;
  5. (“^\w+([-+.]\w+)@\w+([-.]\w+). \ w + ([-] \ w +) * $”);
  6. You can enter only A string of 26 letters and numbers: “^[a-za-z0-9]+$”);
  7. Integer or decimal: ^[0-9]+.{0,1}[0-9]{0,2}$
  8. You can only enter a number: “^[0-9]*$”.
  9. Only n digits can be entered: “^\d{n}$”.
  10. You can enter at least n digits: “^\d{n,}$”.
  11. Only m to N digits can be entered: ^\d{m,n}$.
  12. Can only enter the number of zero and non-zero start: “^ (0 | [1-9] [0-9] *) $”.
  13. You can only enter a positive real number with two decimal places: “^[0-9]+(.[0-9]{2})? $”.
  14. Only positive real numbers with 1 to 3 decimal digits can be entered: “^[0-9]+(.[0-9]{1,3})? $”.
  15. You can only enter a non-zero positive integer: “^+? [1-9] [0-9] * $”.
  16. You can only enter a non-zero negative integer: “^-[1-9][]0-9″*$.
  17. You can enter only three characters: “^.{3}$”.
  18. You can only enter A string of 26 letters: “^[a-za-z]+$”.
  19. Only 26 uppercase characters can be entered: “^[a-z]+$”.
  20. You can enter only 26 lowercase letters: ^[a-z]+$.
  21. Verify that ^%&’,; =? \” characters: “[^%&’,;=?\x22]+”.
  22. Only Chinese characters can be entered: “^[\u4e00-\u9fa5]{0,}$”.
  23. Verify URL: “^http://([\w-]+.” +[\w-]+(/[\w-./?%&=]*)? $”.
  24. Verify 12 months of the year: “^(0? [1-9] | 1 [2-0]) $” correct format is: “01” ~ “09” and “1” to “12”.
  25. Verify 31 days of a month: “^((0? [1-9]) | | 2 (1) ([0-9]) | | 31) $30 “is the correct format for;” 01″ to “09” and 1″ to “31”.
  26. Access to date a regular expression: \ d {4} [. | | -] \ d {12} \ 1 – \ [| – |.] \ d {31} 1 – \ \ day?

Comment: Can be used to match most year, month and day information.

  1. Match double-byte characters (including Chinese) : [^\x00-\ XFF]

Note: Can be used to calculate the length of a string (2 for a double-byte character, 1 for an ASCII character)

  1. Match a regular expression with blank lines: \n\s*\r

Note: Can be used to delete blank lines

  1. A regular expression that matches HTML tags: <(\S*?) [^ >]>.? < / a > | <. *? />

Comments: The versions circulating online are terrible, and the one above is only a partial match. It still doesn’t work with complex nested tags

  1. Regular expression matching fore and aft white space characters: ^ | \ \ s * * s $

Note: Useful expression that can be used to remove whitespace characters (including Spaces, tabs, feed characters, and so on) at the beginning and end of a line

  1. [a-za-z]+://[^\s]*

Comment note: the version function that spreads on the net is very limited, above this can satisfy the demand basically

  1. Whether the matching account is valid (starting with a letter, allowing 5-16 bytes, and underscore letters and digits) : ^[a-za-z][a-za-z0-9_]{4,15}$

Comment: Form validation is useful

  1. [1-9][0-9]{4,}

Comment: Tencent QQ number from 10 000 start

  1. [1-9]\d{5}(? ! \d)

Remark: Chinese postal codes are 6 digits

  1. Match the IP address: ((2 [0-4] \ d 25 [0 to 5) | | [01]? \d\d?) .). {3}(2[0-4]\d|25[0-5]|[01]? \d\d?)