String objects and regular expressions

一·String object method

Concept: multiple characters Read-only character array………String is essentially an array

and an array

1. The original array can be modified at will, but the string is read-only character array. Once created The content cannot be changed

2. The type is different: array is Array, string is not String. span>

same

1. You can use [i] to access an element or character

2. All have length attributes to record the number of elements or characters

3. There can be for loops Traverse elements or characters

4. Both support slice selection of sub-arrays or strings p>

Common API

toLowerCase(): Convert the string to lowercase and return a new string

var str="Hello World";

var str1=str.toLowerCase();
console.log(str); //Hello World
console.log(str1); //hello world

toUpperCase(): Convert the string to uppercase and return the new string

var str="hello world";

var str1=str.toUpperCase();
console.log(str); //hello world
console.log(str1); //HELLO WORLD

charAt() : Get the character at the specified subscript position

var str ="hello world";

var str1=str.charAt(6);
console.log(str1); //w

charCodeAt(): Returns the unicode encoding of the character at the specified subscript position

var str="hello world";

var str1=str.charCodeAt(1);
var str2=str.charCodeAt(-2); //NaN
console.log(str1); //101

split(): Split a string into an array of strings.

var str="AA BB CC DD";

var str1=str.split("");//If an empty string ("") is used as a separator, each character of the string will be split
console.log(str1);// ["A", "A", "", "B", "B"," ", "C", "C", "", "D" , "D"]

var str2=str.split(" "); //Take a space as a separator
console.log(str2); //["AA" "BB" "CC" "DD"]

var string1="1:2:3:4:5";
var str4=string1.split(":");
console.log(str4); // ["1", "2", "3", "4", "5"]

< p> The slice() method can extract a part of a string and return the extracted part as a new string.

Extract all characters starting from position 6:


Output: happy world!

Extract all characters from position 6 to position 11:

Output: happy

substr() method can extract from the string start The specified number of characters starting from the subscript.

Use substr() to extract some characters from a string:

1.
Output: lo world!

2.
Output: lo worl

The concat() method is used to connect two or Multiple strings.

 The output of the above code is:


Hello world!

replace(): Use some characters in the string Replace some other characters, or replace a substring that matches the regular expression.

var str="hello WORLD";

var reg=/o/ig; //o is the keyword to be replaced and cannot be quoted, otherwise the replacement will not take effect, i ignores case, and g means global search.
var str1=str.replace(reg,"**")
console.log(str1); //hell** W*RLD

Four ways to find keywords span>

1. Find the position where a fixed keyword appears< /p>

var i =string.indexog(“keywords”) by default starts from 0, by default it can only find the position of one occurrence< /span>

var str="Hello World";

var str1=str.indexOf("o");
var str2=str.indexOf("world");
var str3=str.indexOf("o",str1+1);
console.log(str1); //2 By default, only find the first keyword position, starting from subscript 0
console.log(str2); //-1
console.log(str3); //7

2. Determine the character Whether the string contains sensitive words that conform to the regular pattern

var i = str.search(/ Regular/i) i means ignoring case. Find the position of the first keyword that meets the requirements of the regular expression in str
Return value: the index of the returned keyword is found, if not found, return -1



Output: 6

3. Use regular expressions to query the specified category Keywords
var arr = str.match(/regular/ig) Find all regular expressions in str The keywords required by the style, saved in an array and returned
By default, only the first one is found, and all the required keywords must be added g
Return value: All sensitive words form an array, if not found, return null

var arr = str.match(/we/gi);
console.log(String(arr));
//Emphasis: if an api is possible If you return null, you must first judge it. Use it when you don’t wait for null.

4. Know where to find the specific content
//var arr = reg.exec (complete character with search String)

Return value: a keyword and position found this time
arr[0]:The content of the keyword If There are groups in the regular arr[n]: automatically save the matching sub-content in the nth group
arr[index]: Current keyword position -> arr.index If not found, return null
After each search, reg.lastIndex will be used The attribute (the next starting position) is modified to the current index + the length of the keyword, which is equivalent to skipping the current keyword and continuing to look back

var str = "On that day, I went to her house, and I said: I’m really big with yours. She said to go on an outing together, I cleaned up hastily, she said: "I'll go and come";

var reg =/我[去草]{1,2}/g;
var arr;
//Fixed usage: find all keywords
//Repetition: Find the keyword in str, as long as it is not equal to null
while((arr=reg.exec(str))!=null){
console.log(arr);
console.log(
`At position ${arr["index"]}
found
Sensitive words ${arr[0]}`
);
}

Two. Regular expressions

RegExp object method

RegExp:

Encapsulate a regular expression and provide an API for finding and verifying using regular expressions

Create known rules for creating direct quantities
var reg=/no/g;// All and / must be added in the regular \/ to be escaped as / div>

console.log(typeof reg);//object object
Dynamically create regular
var reg1=new RegExp(/regular/,”gi”);

The object has 3 methods: test(), exec() and compile().

Regular expressions are strictly case sensitive

< span style="color: #000000; font-size: 15px;">After adding i  , make regular expressions case-insensitive and not commonly used

g   global matching If you find it, you will continue to look for it, if you don’t find it, you will always look for it

m   performs multi-line matching

p>

share picture

share pictures

Exercise: Randomly Generate Tests Certificate code, verify that the input is correct

  < /span>

Test whether the phone number is entered correctly p>

var reg=/^(13|15|18|17)\d{9}$ /;

var str=‘18175693062’;
if(reg.test(str)){
console.log(‘Entered correctly’)
break;
}else{
console.log(‘input error, please re-enter’)
}

Enter the six-digit password to determine if it is correct




Exercise: calculation Questions
ten random addition questions, receive the player’s input results, and then determine the correct Wrong, add 10 points to a question, the game is over, and the total score is given
// If you enter exit, you will exit the game directly






Encapsulate a regular expression and provide the Regular expressions to find and verify the API

Create direct volume creation has been Knowing the rules
var reg=/no/g;// all and / must be in the regular Add \/ to escape to/
console.log(typeof reg);//object object
Dynamically create regular
var reg1=new RegExp(/regular/,"gi");

Create known rules for creating direct quantities
var reg=/no/g;// All and / must be added in the regular \/ to be escaped as /
console.log(typeof reg);//object object
Dynamic creation Regular
var reg1=new RegExp(/regular/,"gi"); < /div>

Create known rules for creating direct quantities

var reg=/no/g;// All and / must be added in the regular \/ before it can be escaped as /

console.log(typeof reg);//object object

Dynamically create regular

var reg1=new RegExp (/Regular/,"gi");

Leave a Comment

Your email address will not be published.