This is the 26th day of my participation in the August More Text Challenge
Hi, I’m Ken
Author: Please call me Ken Link: juejin.cn/user/109118… The copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please indicate the source.
🌊🌈
Part of the content and pictures of the article are from the Internet. If you have any questions, please contact me (there is an official account in the introduction of the home page).
This blog is suitable for just contactJS
And the friends who want to review after a long time.
🌊🌈
5.6_ String object
In JavaScript, string objects provide properties and methods for processing strings, making it easy to find, intercept, replace, and convert strings.
5.6.1_ Use of string objects
String objects are created using new String(). Passing a String in the String constructor saves the String in the returned String object.
Case: demonstration,
// Create a string object
var str = new string('apple');
// Create a string object
console.log (str);
// Output result: string{"apple"}
// Get the string length, output :5
console.log(str.length);
Copy the code
Careful readers will notice that we can use string variable.length, which is much like accessing the length property of an object.
Case: demonstration,
var str = 'apple';
console.log (str.length);
// Output: 5
Copy the code
In fact, strings are a basic wrapper type in JavaScript. The basic wrapper types in JavaScript include String, Number, and Boolean, which are used to wrap basic data types as complex data types, thereby giving them properties and methods as well.
It’s important to note that while Javascript’s basic type-wrapping mechanism allows ordinary variables to access properties and methods like objects, they are not object types.
Case: demonstration,
var obj = new String('Hello');
console.log (typeof obj);
// Output result: object
console.log (obj instanceof String);
// Output result: true
var str = 'Hello';
console.log (typeof str);
// Output: string
console.log (str instanceof String);
// Output result: false
Copy the code
As you can see from the above code, obj returned with new String() is an object, but a normal String variable is not an object, it is just String data.
5.6.2_ Return position by character
A string object provides attributes and methods for retrieving elements
The string object is used to retrieve the attributes and methods of an element:
Members of the | role |
---|---|
indexOf( search Value ) | Gets the position where search Value first appears in the string |
lastIndexOf( search Value ) | Gets the last position of search Value in the string |
Example: Use indexOf() and lastIndexOf() methods,
var str = 'HelloWorld' ;
console.log( str.indexOf('o'));// Get the position where "o" first appears in the string
console.log( str.lastIndexOf('o'));// Get the last position of "o" in the string, return 6
Copy the code
As you can see from the return result, the position starts at 0, the first character of the string is 0, the second character is 1, and so on, the last character is the length of the string minus 1.
Example: Find the position and number of occurrences of all specified elements in a set of strings. The string is’ Hello World, Hello JavaScript ‘.
var str = 'Hello World,Hello Javascript';
var index = str.indexOf('o'); // find the position where the first o appears.
var num = 0; // Set the initial value of o to 0.
while(index ! = -1) {// Determine the result of the return value of indexOf using the while statement
// If the index is not -1, continue the search. This is because indexOf can only find the first one,
// Add index 1 to index 1.
// To continue the search.
console.log (index);// Outputs :4, 7, 17
index = str.indexOf('o', index + 1);
num++;
}
console.log (The number of occurrences of 'o 'is: + num);// the number of o occurrences is :3
Copy the code
Note that a space in a string is also treated as a character.
5.6.3_ Return characters by position
In JavaScript, string objects provide methods to get a character in a string.
The string object is a method used to get a character
Members of the | role |
---|---|
charAt(index) | Gets the character at the index position, evaluated from 0 |
charCodeAt(index) | Gets the ASCII code for the character at the index position |
str [ index ] | Get the character at the specified position (new in HTML5) |
Example: Learn about charAt(), charCodeAt(), STR [subscript],
var str = 'Apple';
console.log (str.charAt(3));// Output :1
console.log (str.charCodeAt(0));// Output result: 65(ASCII code of character A is 65)
console.log(str[0]);// Output result :A
Copy the code
5.6.4_[Case] Statistics on the maximum number of characters and the number of occurrences
Example: Demonstrate the use of the charAt() method. The program counts the number of characters and occurrences in a string
var str = 'Apple';
// Step 1 count the number of occurrences of each character
var o = { };
for (var i = 0; i < str.length; i++) {
var chars = str.charAt(i);
// Use chars to save each character in the string
if( o[chars] ) {
// Use the attributes of the object to make it easy to find elements
o[chars]++;
}else{
o[chars] = 1; }}console.log(o); {A: 1, p: 2, 1:1,e:1}
var max = 0; // Save the maximum number of occurrences
var ch = ' '; // Save the most frequently occurring character
for(var k in o){
if(o[k] > max){ max = o[k]; ch = k; }}// Output result :" the most common occurrence is :p, 2 times"
console.log('The most common character is :' + ch + ', there comes together. ' + max + 'time');
Copy the code
5.6.5_ String Operations
String objects provide properties and methods for intercepting, concatenating, and replacing strings
Methods used by string objects to intercept, concatenate, and replace strings:
Members of the | role |
---|---|
Concat (STRL str2, str3…). | Concatenate multiple strings |
slice(start,[ end ]) | Intercepts a substring from the start to end position |
substring(start [,end] ) | Intercepts a substring from the start position to the end position, essentially the same as slice, but accepts no negative values |
substr(start [, length] ) | Intercepts a substring from the start position to length |
toLowerCase() | Gets the lowercase form of the string |
toUpperfCase() | Gets the uppercase form of the string |
split( [ sparator [, limit] ) | Use the separator separator to separate strings into arrays and limit to limit the number |
replace(str1, str2) | Using str2 to replace str1 in the string returns the replacement, replacing only the first character |
When you operate on a string using the methods in the table above, the result is returned directly from the method’s return value and does not change the string itself.
Case: demonstration,
var str = 'HelloWorld';
str.concat('! '); // Concatenate characters at the end of the string, resulting in HelloWorld!
str.slice(1.3); // Select * from position 1 to position 3
str.substring (5); // Capture the content from position 5 to the end, resulting in: World
str.substring(5.7); // Capture the content from position 5 to position 7, result: Wo
str.substr(5); // Intercepts from position 5 to the end of the string, resulting in: World
str.substring(5.7);// Capture the content from position 5 to position 7, result: Wo
str.toLowerCase(); // Convert the string to lowercase, resulting in helloWorld
str.toUpperCase(); // Convert the string to uppercase, resulting in HELLOWORLD
str.split('1'); // Cut string with "1", result: ["He","","oWor","d"]
str.split('1'.3); // Limit up to 3 cuts, result: ["He","","oWor"]
str.replace('World'.'! ');// Replace string, result: "Hello!"
Copy the code
5.6.6_[Case] Check whether the User Name is valid
Case: The user name must be 3 to 10 in length, and the sensitive word admin cannot be used in any case.
var name = prompt('Please enter username');
if (name.length < 3 || name.length > 10){
alert('The username must contain 3 to 10 characters. ');
} else if (name.toLowerCase().indexOf('admin')! = = -1){
alert('The user name cannot contain the sensitive word admin. ');
}else{
alert('Congratulations, this username can be used');
}
Copy the code
The above code verifies the length of the user name by judging the length attribute; Check whether the user name contains the sensitive word admin by converting it to lowercase. When you implement it, you convert the name to lowercase and then you look it up, and you can use the username and you can check it out regardless of which case combination you use. The indexOf() method returns -1 on lookup failure, so the return value of this method can be used to determine whether the user name contains sensitive words.
5.7_ Value types and reference types
In JavaScript, basic data types (string, number, Boolean, undefined, null) are also called value types, and complex data types (objects) are referred to as reference types. A reference type stores only the address of a reference in a variable. When assigning a value to a variable, it does not make a copy of the object. Instead, it refers to a reference to the same object.
Example: For example, obj1 and obj2 in the following code point to the same object.
// Create an object and hold a reference to it through the variable obj1
var obj1 = {name:'Ming'.age:18};
Obj2 and obj1 refer to the same object
var obj2 = objl;
// Compare whether two variables refer to the same object
console.log (obj2 == obj1); // Output result :true
// Modify the properties of the object with obj2
obj2.name = 'little red';
// Access the object's name property through obj1
console.log (obj1.name) // Output result: small red
Copy the code
After the above code is executed, the obj1 and obj2 variables refer to the same object, and the same object will be operated on either using obj1 or using obj2.
When obj1 and obj2 refer to the same object, if one of the variables (such as obj1) is reassigned to another object, or reassigned to another value, obj1 will no longer reference the original object, but obj2 will still reference the original object.
Case: Demonstrates the above overview:
var objl = name:'Ming'.age: 18 };
var obj2 = objl;
// obj1 points to a newly created object
obj1 = { name: 'little red'.age: 17 };
// obj2 still points to the original object
console.log (obj2.name); // Output result: Xiao Ming
Copy the code
In the above code, line 1 creates an object with the name xiaoming, and initially only obj1 is referenced. After line 2, both obj1 and obj2 reference the object, and after line 4, only obj2 references the object. When an object is referred to by only one variable, if the variable is reassigned, the object is left without any references and is automatically released by JavaScript’s garbage collection mechanism.
When a variable of a reference type is passed as an argument to a function, the effect is similar to that of an assignment between variables. If you modify an object property or method in a function argument, the result that is accessed outside the function through a variable referencing the object is also modified.
Example: To illustrate the above overview,
function change(obj){
obj.name = 'little red'; // Modify the attributes of the object in the function
}
var stu = { name:'Ming'.age: 18 };
change(stu);
console.log (stu.name); // Output result: small red
Copy the code
In the code above, the value of obj.name is modified in the chang() function after the change() function is called. After the modification, the value that is accessed outside the function beyond the stu variable is the modified value, indicating that the variable stu and the parameter obj refer to the same object.
That’s the end of today’s introductory study
Peace
🌊🌈
A Ken HTML, CSS introduction guide (a)_HTML basics a Ken HTML, CSS introduction guide (b)_HTML page elements and attributes a Ken HTML, CSS introduction guide (c)_ text style attributes Ken HTML, CSS introduction guide (four)_CSS3 selector Ken HTML, CSS introduction guide (five)_CSS box model Ken HTML, CSS introduction guide (six)_CSS box model Ken HTML, CSS introduction guide (seven)_CSS box model Ken’s Getting Started with HTML and CSS (8)_CSS box model Ken’s Getting Started with HTML and CSS (9)_ Floating and Positioning Ken’s Getting Started with HTML and CSS (10)_ Floating and Positioning Ken’s getting Started with HTML and CSS (11)_ Floating and positioning Ken’s introduction to HTML and CSS (12)_ The application of forms The introduction to HTML and CSS (13)_ the application of forms (14)_ the application of forms the introduction to HTML and CSS (15)_ the application of forms A Ken HTML, CSS introduction guide (16) _ multimedia technology
Suggest collection 】 【 HTML dry share | challenge the shortest possible time to take you into the HTML (18) suggest collection 】 【 HTML dry share | challenge the shortest time take you into the HTML (19) suggest collection 】 【 HTML dry share | challenge the shortest time take you into the HTML (20)
Suggest collection 】 【 share | JS dry challenge the shortest possible time to take you into the JS (a) suggest collection 】 【 share | JS dry challenge the shortest possible time to take you into the JS (2) suggest collection 】 【 share | JS dry challenge the shortest time to take you into the JS (3) the share | JS dry Recommended collection 】 challenge the shortest time take you into the JS (4) suggest collection 】 【 share | JS dry challenge the shortest time take you into the JS (5) suggest collection 】 【 share | JS dry challenge the shortest time take you into the JS (6) suggest collection 】 【 share | JS dry challenge the shortest possible time to take you into the JS (7) Suggest collection 】 【 share | JS dry challenge the shortest possible time to take you into the JS (eight) suggest collection 】 【 share | JS dry challenge the shortest possible time to take you into the JS (nine) suggest collection 】 【 share | JS dry challenge the shortest possible time to take you into the JS (10)
🌊🌈 About postscript:
Thank you for reading, I hope to help you if there is a flaw in the blog, please leave a message in the comment area or add contact information in the home page of the personal introduction of private chat I thank every little partner generous advice
Original is not easy, “like” + “attention” thanks for your support ❤