String operation exercises of native JS built-in objects

Time:2021-1-20

(1) Get string length

console.log(str.length);   // 33

 

(2) Take out the characters in the specified position, such as 0, 3, 5, 9, etc

console.log(str[0], str[3], str[5], str[9]);   // a a d g

 

(3) Find whether the specified character exists in the above string, such as: I, C, B, etc

console.log(str.indexOf('i'), str.indexOf('c'), str.indexOf('b'));    // -1 -1 1

 

(4) Replace the specified characters, such as: G replaced by 22, SS replaced by B and so on

/*JS high-level writing of the regular expression "g / g", G is the global search*/
console.log(str.replace(/g/g, '22'));  // abaasdff222222hhjjkk22fddsssss3444343
console.log(str.replace(/ss/g, 'b'));  // abaasdffggghhjjkkgfddbbs3444343

 

(5) Intercept the string from the specified start position to the specified end position, such as: get 1-5 string

console.log(str.substr(0, 5));   // abaas

 

(6) Find the most frequent character and the most frequent character in the string

var newArr = {};
for (var i = 0; i < str.length; i++) {
    var char =  str.charAt (i) ; // charat() returns the character of the index object
    if (newArr[char]) {
        Newarr [char] + +; // times plus 1, "object [key] = 1" assigns value to each traversed object attribute
    } else {
        Newarr [char] = 1; // if it appears for the first time, the number is 1
    }
}
console.log (newarr); // output a complete object, recording each character and its occurrence times

Var max = 0; // the maximum number of occurrences of the first for loop
For (VaR key in newarr) {// key is the attribute, that is, string, newarr is the object, and newarr [key] is the attribute value
    if (max < newArr[key]) {
        Max = newarr [key]; // max always stores the one with the largest number of times
    }
}
For (VaR key in newarr) {// the second for loop finds the character corresponding to the maximum number of occurrences
    if (newArr[key] == max) {
        console.log ("the most characters are" + key + '\ t' + "and the number of occurrences is" + Max ");
    }
}

 

(7) Add “@” at both ends of traversed characters

var strArr =  str.split ('); // the method of splitting a string into a string array
var newStr = [];
for (var i = 0; i <  strArr.length ; I + +) {// traversal
    var newChar = '@' + strArr[i] + '@';
    Newstr + = newchar; // connect newchar strings one by one
}
console.log(newStr);