JavaScript built-in object - String object

Basic packaging content

To facilitate the operation of basic data types, js also provides three special reference types
: String, number, Boolean
The basic wrapper type is to wrap simple data types into complex data types
Thus, there are properties and methods

The principle is
Wrap complex data into simple types
Use this complex data type for some operations
Finally, the complex data type is transferred back to the simple data type
The above is automatically completed by js

Immutability of string

The immutability of a string refers to the immutability of the value inside. The input looks like the content has changed, but in fact, the address has changed

When the string variable is re assigned, the previously saved string of the variable will not be modified. If the string is still re assigned in memory, it will open up space in memory again. This feature is the immutability of the string.
Due to the immutability of strings, there will be efficiency problems when splicing a large number of strings

Problems caused by the immutability of strings:
Memory consumption, so try not to do a lot of string splicing

Return position according to character

The string can be manipulated by calling some methods through the basic wrapper type,
Returns the position of the specified character, similar to that of the array

Number of location finding (difficulty)

We can use the above method to count the position and number of times a character appears in the string

position

indexOf()

As shown in the figure

At the same time, we can skip the first few characters and start to find the position
As shown in the figure

frequency

The idea is as follows

First create a string variable
Look for the number and location of q occurrences

var a ='qwqeqeqrqrqrqrqewqvgq';

Create a variable equal to 0 to count the number of occurrences

var b =0;

Using indexOf() to add numbers, you can start to find the number you add in the first place
We can create a variable equal to the position where the first q appears

var index = a.indexOf('q');

Then start using the loop to find the location and index value
Here we use the while loop

while (index != -1) {
  //If the representative finds it
  console.log('Location is'+index);
  // Print out position
  b++
  // Representative times
  index = a.indexOf('q',index+1);
  // If it appears, start from the back of q
}
console.log(b);
// Number of printing occurrences

The complete code and results are as follows

Returns characters based on position

Strings can also be manipulated by calling some methods through the basic wrapper type
The method is as follows

charAt()

charAt() returns the character at the specified position
As shown in the figure

Traversing strings with charAt()

The code is as follows

var a = 'biu';
for(var i = 0 ; i<a.length;i++){
  console.log(a.charAt(i));
}

charCodeAt()

Gets the ASCII code of the string at the specified location

ASCII codes are as follows

str[]

This is a new addition to html5 to get the character at the specified position
It is most convenient not to consider compatibility

var a = 'biu';

alert(a[2])

Count the characters with the most occurrences (difficulty)

1 first create an empty object to store

var a = 'qwwqqqqqqertt';
var o = {}

2 traversal string

for(var i = 0; i <a.length; i++) {
  
}

3 set a variable equal to the ith character in the string

var c =a[i]
//Because c equals a[i], c here represents every character in the string

4 establishment conditions

if(o[c]){
o[c]++
//o[c] represents the attribute value of the object. If it is found again, add one, that is, the attribute value plus 1, which is equivalent to the quantity plus 1 
}else{
o[c] = 1
//Represents the first time it is found and assigned a value of 1
}

At present, the complete code is as follows

 var a = "qwwqqqqqqertt";
      var o = {};
      for (var i = 0; i < a.length; i++) {
        var c = a[i];
        //  amount to
        if (o[c]) {
          o[c]++;
        } else {
          o[c] = 1;
        }
      }

Output object
obtain

After counting the code, we are looking for the most characters and their number

Let's set a variable as the maximum value first
It should be noted that when we assign values, the maximum value cannot be a positive number to prevent the array or objects from being all 1 or decimal

var max = -1 

At the same time, a variable is set to represent the property name of the object

var m ;

6 traversal object

 for(var key in o) {
    
  }

7. Set the condition. If the variable is larger than the maximum value we set, assign the attribute value to the object we set the maximum value
At the same time, let the variable representing the attribute name set by us be equal to key (attribute name);

 if(o[key] > max) {
          max =o[key];
          m =key
        }

The output results are as follows


The complete code is as follows

 var a = "qwwqqqqqqertt";
      var o = {};
      for (var i = 0; i < a.length; i++) {
        var c = a[i];
        if (o[c]) {
          o[c]++;
        } else {
          o[c] = 1;
        }
      }
      console.log(o);
      var max = -1;
      var m ;
      for(var key in o) {
        if(o[key] > max) {
          max =o[key];
          m =key
        }
      }
      console.log(max);
      console.log(m);

String operation method

concat() splicing

concat(str1,str2,str3..)

The concat() method is used to connect two or more strings, equivalent to the + sign
However, the + sign is simpler, more convenient and commonly used

substr() intercepts key points

 substr(start,length)

start represents the starting position
length represents the number to be fetched
What needs to be distinguished is that interception is not deletion

slice() interception

slice(start,end)

Intercept from the start position to the end position
end do not take

You can also take a negative number

substring() interception

substring(start ,end )

substring() is the same as slice
Intercept from the start position to the end position
end do not take
However, negative numbers cannot be taken

Replace() replace string

replace(String to be replaced, string to be replaced with)



However, it should be noted that if there are many identical characters in a string, they need to be replaced
A while loop is required

First, use indexOf() to set the condition

  while (str.indexOf("qwe") != -1) {
  //Represents qwe in the string until it cannot be found
  }

Then set the loop body

 str = str.replace("qwe", "zxc");

The complete code is as follows

      var str = "qwertyuioqwertyuioqwertyuio";

      while (str.indexOf("qwe") != -1) {
        str = str.replace("qwe", "zxc");
      }

Print and try the results

split() splits the string

The format is as follows

character string.split("Split character")

The split() method is used to split strings, which can be split into arrays. After segmentation, a new array is returned.

join() add

join('Symbol')

The join() method is used to merge arrays. After merging, a string is returned.

String flip

Because the array can be flipped, we can use the above two codes (spit () and join ()) to flip the string
Generally

character string.spilt().reverse().join()

Case

toLocaleUpperCase() uppercase

character string.toLocaleUpperCase() 

Tolocalelovercase() lowercase

character string.toLocaleLowerCase() 

Keywords: Javascript ECMAScript

Added by flashpipe on Sat, 12 Feb 2022 03:19:32 +0200