string

1. String properties

A string property, like an array, has a length property. Indicates the length of a string. Each letter, Chinese character, number, punctuation mark, and space can be counted as a length. call

Note: Strings also have index values, starting from 0

var str = 'It's so stuffy today, it feels like 35°C';
console.log(str.length);
/ / 17
Copy the code

2. String methods

  1. charAt()

    Represents the string corresponding to the index value, and the argument is the index value

    var str = 'It's so stuffy today, it feels like 35°C';
    console.log(str.charAt(3));
    / / gas
    Copy the code
    // String traversal
    for (var i = 0; i < str.length; i++) {
      console.log(str.charAt(i));
    }
    // The air is so stuffy today, I feel the temperature is 35 ° C
    Copy the code
  2. indexOf()

    Represents the position where the string first occurs. Return -1 if none exists

    var str = 'It's so stuffy today, it feels like 35°C';
    console.log(str.indexOf('day'));
    / / 1
    Copy the code
  3. concat()

    Represents the concatenation of strings. The arguments can be one or more strings, separated by commas, and the return value is a new string, unchanged

    var str = 'It's so stuffy today, it feels like 35°C';
    var strNew = str.concat('I need air conditioning'.'He wants to eat popsicles.');
    console.log(str);
    // It's so stuffy today, I feel like the temperature is 35°C
    console.log(strNew);
    // It's so stuffy today. It feels 35°C. I need air conditioning
    Copy the code
  4. slice(start, end)

    Represents a string truncating the index value from start to end, including start but not end, can be positive, can be negative, and can not write end

    var str = 'It's so stuffy today, it feels like 35°C';
    var str2 = str.slice(3.9);
    var str3 = str.slice(-9, -3);
    var str4 = str.slice(3);
    console.log(str2);
    // The air is too stuffy
    console.log(str3);
    // The temperature is 3
    console.log(str4);
    // The air is so stuffy that it feels 35°C
    Copy the code
  5. split()

    A string truncated with a character to get a new array, argument: character, return value: array

    var str = 'aaabcccbddkbhhj';
    var arr = str.split('b');
    console.log(arr);
    // [ 'aaa', 'ccc', 'ddk', 'hhj' ]
    Copy the code
  6. substr(start, houmany)

    Represents a number of strings truncated from an index value

    var str = 'It's so stuffy today, it feels like 35°C';
    console.log(str.substr(2.5));
    // It's too stuffy
    console.log(str.slice(2.7));
    // It's too stuffy
    Copy the code
  7. substring(start, end)

    Indicates a string from start to end. No negative value can be used

    var str = 'It's so stuffy today, it feels like 35°C';
    console.log(str.substring(2.7));
    // It's too stuffy
    console.log(str.substring(7.2));
    // It's too stuffy
    Copy the code

    Note: the parameter position of this method can be exchanged, will automatically judge, including small large, excluding large

  8. toUpperCase() toLowerCase()

    ToUpperCase (): converts toUpperCase letters

    ToUpperCase (): converts to lowercase letters

    var str1 = 'vience';
    console.log(str1.toUpperCase());
    // VIENCE
    var str2 = 'VIENCE';
    console.log(str2.toLowerCase());
    // vience
    Copy the code

Example: Capitalize the first letter of each letter

var str = 'everything is good in its season';
// We need to get an array of each word
// Then iterate over each word in the array to capitalize the first letter
// Finally put the array with Spaces
var arr = str.split(' ').map(item= > item.charAt(0).toUpperCase() + item.slice(1));
var strNew = arr.join(' ');
console.log(strNew);
// Everything
Copy the code

Regular expression

Regular expressions are just rules for matching strings. The data type is an object (reference type), and the re is often used for form validation

Experience: Enter a phone number to 000-12345678

Var call = prompt(" Please enter phone number "); var reg = /^\d{3}-\d{8}$/; If (reg.test(call)) {console.log(" entered correctly "); } else {console.log(" Input error, please reenter "); } // The input is correctCopy the code

1. Overview of re

Regular expression, or RegExp for short, is a combination of characters used to match strings. It is often used for form verification

Create: The use of re literals is common

Literals: expressions

var reg = /\d+/    // Indicates one or more digits
var reg = /\s+/    // Indicates one or more whitespace characters
var reg = /abcd/    // Four characters must be abcd in a fixed order
Copy the code

Method 2.

  • String methods (string calls, regular expressions as arguments)
  • Regular expression methods (regular expression calls, strings as arguments)

2.1 String methods

  1. split()

    Cut the original string according to the matching string

    var str = 'aaabbjdkbbbbjskblkk';
    var reg = /b+/;
    console.log(str.split(reg));
    // [ 'aaa', 'jdk', 'jsk', 'lkk' ]
    
    var str1 = 'v i   e  n    c   e';
    var reg1 = /\s+/;
    console.log(str1.split(reg1));
    // [ 'v', 'i', 'e', 'n', 'c', 'e' ]
    Copy the code
  2. match()

    Returns an array of matching results using a regular expression compared to a string after a character

    Used to locate the matching output of a string or re

    // The argument is normal string yes
    var str = 'abobosjkfjffkl';
    console.log(str.match('obo'));
    // [ 'obo', index: 2, input: 'abobosjkfjffkl', groups: undefined ]
    // inde indicates the index value of the location
    
    Copy the code
    
    var str = 'abo osjko ofjo offkl';
    console.log(str.match(/o\s+o/));
    // [ 'o o', index: 2, input: 'abo osjko ofjo offkl', groups: undefined ]
    // inde indicates the index value of the location
    console.log(str.match(/o\s+o/g));
    // [ 'o o', 'o o', 'o o' ]
    
    var str1 = "BOSS/CRM_ Chu Xindi _13739186228, channel load _ Liu Jinsong _13905182960";
    var res = str1.match(/\d{11}/g);
    console.log(res);
    // ['13739186228', '13905182960']
    Copy the code

    Note: If g is not written and only the first string matching the field is printed, an array of all matching strings will be printed with g

  3. search()

    Searches with a regular expression or a specified string, and returns the first occurrence of a match

    var str = 'aboaosjkoaaaaofjoaaoffkl';
    // Specifies a string
    console.log(str.search('oa'));
    / / 2
    // Regular expressions
    console.log(str.search(/oa+o/));
    / / 2
    // Search only the first plus g will not search globally
    console.log(str.search(/oa+o/g));
    / / 2
    Copy the code
  4. replace(old, new)

    Compare the string directly with the regular expression, and then replace the matched string with the new string

    Parameter: old: matched string new: new string

    var str = 'www.baidu.com';
    console.log(str.replace('baidu'.'yunxicn'));
    // www.yunxicn.com
    console.log(str.replace(/baidu/.'yunxicn'));
    // www.yunxicn.com
    
    var strName = 'v i e n c e';
    console.log(strName.replace(/\s+/g.' '));
    // vience
    Copy the code

2.1 Regular expression method

  1. exec()

    Returns an array representing the position of the matched string within the original string. Even if a global match g returns only the first occurrence (similar to the search method)

    var str = 'aaabcdddabced';
    
    // String methods - global matching
    console.log(str.match(/abc/g));
    // [ 'abc', 'abc' ]
    
    // Regular method
    var reg = /abc/;
    console.log(reg.exec(str));
    // [ 'abc', index: 2, input: 'aaabcdddabced', groups: undefined ]
    Copy the code
  2. test()

    Check whether the regular expression matches in a string. Used for form verification. Returns true, but does not return fasle

    console.log(/\t/.test('v	ience'));
    // true
    console.log(/\n/.test(`v
    ience`));
    // true
    Copy the code

Regular expression terms and operators

1. Exact match

Regular expressions: Regular characters are made up of ordinary characters and special characters (metacharacters). Regular characters include upper and lower case letters and numbers, and metacharacters have special meanings

JavaScript is commonly used in the special characters () [] {} \ ^ $|? * +. Etc

We must use escape symbols if we use such letters. For example: \^ \

There are no special symbols or operators in the regular expression we are matching. In order to match constants, ordinary characters, we can only do exact matches. Characters appearing in the string must be written directly in the re.

// Test for ABC in string abcnDDjgkgk
// An exact match must have three letters ABC in a fixed order
console.log(/abc/.test('abcnddjgk'));
// true
Copy the code

2. Predefined special characters

\t: /\t/: TAB character

\n: /\n/: Carriage return

\ F: /\f/: page feed character

\b: /\b/: Space

// The space below is a TAB character
console.log(/\t/.test('v	ience'));
// true
console.log(/\n/.test(`v
ience`));
// true
Copy the code

3. Character sets

We have previously used a character matching has been recruited, when you want to match a character with a character class, you need to use the character set

Character set: [] Writes the possibilities of a class of letters within brackets

  • Simple class

    Multiple characters of the re correspond to one character, and we enclose them with [] so that the whole [] corresponds to a string

    // [ABC] indicates that a character set can be a, B, or C
    var str = 'sanasdndjkdscndsbnb';
    console.log(str.match(/s[abc]n/g));
    // [ 'san', 'scn', 'sbn' ]
    Copy the code
  • Scope of the class

    There are too many characters to match, so you can use ranges to include possibilities

    Example: [A-z] [A-z] [0-9]

    console.log(/[a-z]/.test("See if there's a" Ymy."));
    // true
    console.log(/ [0-9].test("Let's see if we have a (010) number."));
    // true
    Copy the code
  • Negative class

    [followed by a metacharacter ^ to invert, indicating that the match cannot be words inside parentheses

    // [^ ABC]: indicates the possibility of a character set, not a, b, c
    var str = 'sanasdndjkdscndsbnbskn';
    console.log(str.match(/s[^abc]n/g));
    // [ 'sdn', 'skn' ]
    Copy the code
  • Combination of the class

    Match single characters of different types with brackets

    var str = 'sanasdndjkdscndsbnbsknsYn';
    console.log(str.match(/s[a-zA-Z0-9]n/g));
    // [ 'san', 'sdn', 'scn', 'sbn', 'skn', 'sYn' ]
    Copy the code

4. Character boundaries

  • ^

    Beginning: indicates that the string can match the string after ^ (cannot be written in brackets).

    console.log(/^hello/.test('hello vience'));
    // true
    console.log(/^ello/.test('hello vience'));
    // false
    Copy the code
  • $

    End: indicates that the string can match the string before $

    console.log(/vience$/.test('hello vience'));
    // true
    console.log(/vienc$/.test('hello vience'));
    // false
    Copy the code
  • \b

    Word boundaries: Used to find a match at the beginning or end of a word

    var str = 'hello vience';
    console.log(str.match(/\b\w+\b/));
    // [ 'hello', index: 0, input: 'hello vience', groups: undefined ]
    console.log(str.match(/\b\w+\s+\b/));
    // [ 'hello ', index: 0, input: 'hello vience', groups: undefined ]
    console.log(str.match(/\b\s+\w+\b/));
    // [ ' vience', index: 5, input: 'hello vience', groups: undefined ]
    console.log(str.match(/\b\w+\b/g));
    // [ 'hello', 'vience' ]
    Copy the code
  • \B

    Non-word boundaries: Used to find matches that are not at the beginning or end of a word

    var str = 'hello vience';
    console.log(str.match(/\B\w+\B/g));
    // [ 'ell', 'ienc' ]
    console.log(str.match(/\B\w+\B/));
    // [ 'ell', index: 1, input: 'hello vience', groups: undefined ]
    console.log(str.match(/\B\s+\w+\B/g));
    // null
    Copy the code

5. The modifier

  • g

    G: Global matching: matches in the global scope

    console.log('banana'.match(/na/));
    // [ 'na', index: 2, input: 'banana', groups: undefined ]
    console.log('banana'.match(/na/g));
    // [ 'na', 'na' ]
    
    var str = "BOSS/CRM_ Chu Xindi _13739186228, channel load _ Liu Jinsong _13905182960";
    console.log(str.match(/\d{11}/));
    // ['13739186228', index: 13, INPUT: 'BOSS/ crm_13739186228, groups: undefined ']
    console.log(str.match(/\d{11}/g));
    // ['13739186228', '13905182960']
    Copy the code
  • i

    I: case insensitive: case insensitive

    console.log('banaNa'.match(/Na/));
    // [ 'Na', index: 4, input: 'banaNa', groups: undefined ]
    console.log('banaNa'.match(/Na/i));
    // [ 'na', index: 2, input: 'banaNa', groups: undefined ]
    Copy the code
  • Colleagues use multiple modifiers g and I (in no order)

    console.log('baNana'.match(/na/gi));
    // [ 'Na', 'na' ]
    Copy the code

6. Predefined classes

JavaScript defines some special characters for us in advance, which are shorthand for a class of characters, some special character set

  • .

    [^\n\r] : represents any character except newline and carriage return

    var reg = / ^. + $/;
    console.log(reg.test('@ # $% & ^'));
    // true
    console.log(reg.test('jfkf'));
    // true
    console.log(reg.test('12223'));
    // true
    console.log(reg.test(`a
    $@`));
    // false
    Copy the code
  • \d

    [0-9] : indicates a digit

    var reg = /^\d+$/;
    console.log(reg.test('961113'));
    // true
    console.log(reg.test('9b1113'));
    // false
    Copy the code
  • \D

    [^0-9] : indicates non-numeric characters

    var reg = /^\D+$/;
    console.log(reg.test('961113'));
    // false
    console.log(reg.test('[email protected]'));
    // true
    Copy the code
  • \w

    [A-ZA-Z_0-9] : Word characters (upper and lower case letters, underscores)

    var reg = /^\w+$/;
    console.log(reg.test('vience'));
    // true
    console.log(reg.test('vi ence'));
    // false
    console.log(reg.test('[email protected]'));
    // false
    Copy the code
  • \W

    [^ A-zA-z_0-9] : non-word characters

    var reg = /^\W+$/;
    console.log(reg.test('vience'));
    // false
    console.log(reg.test('vi ence'));
    // false
    console.log(reg.test('@ # $% ^ & *'));
    // true
    console.log(reg.test('@ # $% ^ & * 89'));
    // false
    Copy the code
  • \s

    [\t\n\*OB\f\r] : empty character

    var reg = /^\s+$/;
    console.log(reg.test(' '));
    // true
    console.log(reg.test('12'));
    // false
    console.log(reg.test(`
    `));
    // true
    Copy the code
  • \S

    [^\t\n\*OB\f\r] : non-null character

    var reg = /^\S+$/;
    console.log(reg.test(`
    `));
    // false
    console.log(reg.test('vience89'));
    // true
    Copy the code

7. Quantifiers

Quantifier usage: {}

  • {n} : hard quantity, indicating a fixed number of occurrences of a string (n is a constant value)

    var reg = /ab{2}c/, reg1 = /a[a-z]{3}c/;
    console.log(reg.test('abbc'));
    // true
    console.log(reg.test('abc'));
    // false
    console.log(reg.test('abbbc'));
    // false
    console.log(reg1.test('avuec'));
    // true
    Copy the code
  • {n,m} : soft quantifier, indicating at least n times, at most m times (when M is omitted, indicating at least n times)

    var reg = C / / ab {3, 6}, reg1 = /a[a-z]{3,}c/;
    console.log(reg.test('abbbc'));
    // true
    console.log(reg.test('abbc'));
    // false
    console.log(reg.test('abbbbbbbbc'));
    // false
    console.log(reg1.test('abbbbbbbbc'));
    // true
    console.log(reg1.test('abbc'));
    // false
    console.log(reg1.test('abbbc'));
    // true
    Copy the code
  • ? : equal to {0,1} : indicates 0 or 1 occurrences

    var reg = /ab? c/;
    console.log(reg.test('ac'));
    // true
    console.log(reg.test('abc'));
    // true
    console.log(reg.test('abbc'));
    // false
    Copy the code
  • + : the same as {1,} : indicates the occurrence of at least one time

    var reg = /ab+c/;
    console.log(reg.test('abc'));
    // true
    console.log(reg.test('abbc'));
    // true
    console.log(reg.test('ac'));
    // false
    Copy the code
  • * : equal to {0,} : indicates 0 or more occurrences (any number of times)

    var reg = /ab*c/;
    console.log(reg.test('abc'));
    // true
    console.log(reg.test('abbbc'));
    // true
    Copy the code

    Note {n,m} : there is no space before or after the comma between nm

Grouping 8.

Quantifiers, though, help us deal with a row of closely connected characters of the same type. But this is not enough, we use brackets to represent the range selection, and curly brackets to represent the repetition tree. If we want to retrieve multiple characters, we need to group them with parentheses.

var reg = /(bye){2}/, reg1 = /(bye)+/;
console.log(reg.test('vience byebye'));
// true
console.log(reg.test('vience byebyy'));
// false
console.log(reg1.test('vience byebye'));
// true
Copy the code

9. Or operator

Regular expressions can use or operator |

// Either a or bye
var reg = /a|bye/;
console.log(reg.test('aye'));
// true
console.log(reg.test('bye'));
// true

var reg1 = /(a|bye){1}/;
console.log(reg1.test('a'));
// true
console.log(reg1.test('bye'));
// true
console.log(reg1.test('aye'));
// true
console.log(reg1.test('byebye'));
// true
console.log(reg1.test('bbe'));
// false

// Either 3 letters or 2 numbers
var reg2 = /([a-z]{3})|([0-9]{2})/;
console.log(reg2.test('abc'));
// true
console.log(reg2.test('89'));
// true

var reg3 = /([a-z]{3})|([0-9]{2}){2}/;
console.log(reg3.test('8989'));
// true
console.log(reg3.test('vience'));
// true
Copy the code

10. Grouping back references

The substring captured by the regular expression’s matching group is numbered by the \ number (inside the regular expression), and the $number (outside the regular expression), counting from 1

  • Number in a regular expression

    console.log(/(bye)\1/.test('byebye'));
    // true
    console.log(/(bye){2}/.test('byebye'));
    // true
    console.log(/(bye)\1/.test('bye'));
    // fasle
    console.log(/([a-z]{3})\1/.test('abcabc'));
    // true
    console.log(/([a-z]{3})\1/.test('xyzabc'));
    // fasle
    console.log(/([a-z]{3})\1{2}/.test('xyzxyzxyz'));
    // true
    Copy the code
  • The number outside the regular expression

    console.log("123 * 456".replace(/(\d{3})\*(\d{3})/.'$2 * $1'));
    / / 456 * 123
    
    console.log("123 * 456".replace(/(\d{3})\*(\d{3})/.function (match, $1, $2) {
      return $2 + The '*' + $1;
    }));
    / / 456 * 123
    
    console.log("123 * 456".replace(/(\d{3})\*(\d{3})/.function (match, $1, $2) {
      return $1 + $2;
    }));
    / / 123456
    
    console.log("123 * 456".replace(/(\d{3})\*(\d{3})/.function (match, $1, $2) {
      return parseInt($1) + parseInt($2);
    }));
    / / 579
    Copy the code

11. Chinese

Match Chinese: [u4e00-u9fa5], is a fixed usage, Chinese can only be expressed in regular expressions, can match Chinese simplified/traditional Chinese

var reg = /^[\u4e00-\u9fa5]+$/
console.log(reg.test('games'));
// true
console.log(reg.test('LJ Games HW Youth'));
// false
console.log(reg.test('games'));
// true
Copy the code