This is the fourth day of my participation in Gwen Challenge

String

Get a single character

let str = "abcdef";
str.charAt(1) == str[1]   // true "b"
str.charAt()		  // "a"   
str.charAt(6)             / / ""
Copy the code

Here STR is primitive, but can still be called as an object. When the method is called, three steps take place.

  1. Create an instance of String;
  2. Call a specific method on the instance;
  3. Destroy instance
let str = "abcdef";
str.length          / / 6
str.length = 2;
str.length          / / 6
Copy the code

Not on STR itself, but on the newly created instance, which is destroyed as soon as it is created.

const obj = {
    toString() { return 1; }}let str = "abcdefg";
str[obj] == "b";   // true
let arr = [1.2.3.4];
str[obj] == 2;     // true
Copy the code

The String() transformation function is called in [].

Immutable string

A string is of primitive type, so it has no attributes of its own. When the primitive value calls the attribute, an automatic wrapper mechanism will occur. A wrapper class corresponding to the primitive type is created, and the attribute is destroyed after the call.

let str = "abcd";
str.length;       		/ / 4
str.length = 3    
str.length;       		/ / 4
str.name = "alphabet";
str.name;                       // undefined
// ----------------------------------------
let strObj = new String("abcd");
strObj.length = 2;
strObj.length;          / / 4
Copy the code

The length property of a String cannot be overridden. That is, strings are immutable and cannot be changed once a value is created. To change a string value in a variable, you must first destroy the original string and then save the new string to the variable.

console.log(strObj);
// String {"abcd"}
// 0: "a"
// 1: "b"
// 2: "c"
// 3: "d"
// length: 4
Copy the code

A String object is an array of native classes. The length property cannot be changed.

String static method

String.fromCharCode()

Enter one or more Unicode encodings to return the corresponding characters.

String.fromCharCode(65.66.67.68);    // "ABCD"
String.fromCharCode(32) 		// "" space
String.fromCharCode(9)                  // "" TAB character
Copy the code

String instance method

In the String. On the prototype

charCodeAt()

Returns the Unicode code for the character corresponding to the index position of the string.

let str = "abc";
str.codeCharAt(1);
// The unicode code for b is 98
Copy the code

concat()

Concatenate two string texts and return a new string. The original string is not affected.

let str = "123";
let s1 = "456";
let s2 = "789";
let s3 = "ABC";
let newStr = str.concat(s1,s2,s3);
// "123456789ABC"
Copy the code

The parameter is converted to a string before concatenation.

It is strongly recommended to use the assignment operators (+, +=) instead of the concat method.

includes()

Determines whether a string contains another string. Case sensitive.

str.includes(searchString[, position])
Copy the code

The searchString argument is converted to a string before being judged.

Position is an optional argument that searches for substrings at the index position of the current string. The default value is 0.

endsWith()

Determines whether one string is at the end of another string. Case sensitive.

String.prototype.endsWith = function(search, this_len) {
    // search Specifies the string to search for
    This_len The length of the string being searched, which is the end can be controlled
    if (this_len === undefined || this_len > this.length) {
        this_len = this.length;
    }
    // Take the length of the search string from the end and compare it with the search string. Returns a Boolean value.
    return this.substring(this_len - search.length, this_len) === search;
};
Copy the code
let str = "endsWith";
let b = str.endsWith("With"); // true
Copy the code

startsWith()

Determines whether one string is at the beginning of another string. Case sensitive.

if (!String.prototype.startsWith) {
    Object.defineProperty(String.prototype, 'startsWith', {
        value: function(search, pos) {
            // There is something in this stringpos = ! pos || pos <0 ? 0 : +pos;
            // Intercepts the length of the given string from the specified position. Compare.
            return this.substring(pos, pos + search.length) === search; }}); }Copy the code

indexOf()

Returns the index of the specified searchValue that first occurs in the String calling it, searched from fromIndex. If the value is not found, -1 is returned.

str.indexOf(searchValue [, fromIndex])
Copy the code

See MDN for details.

lastIndexOf()

Returns the index of the last occurrence of calling the specified value of String, searched from back to front at the specified fromIndex position in a String. Returns -1 if this particular value is not found.

padEnd()

Fills the end of the current string with the specified string until the specified length is reached. Returns a new string.

if (!String.prototype.padEnd) {
    // targetLength Specifies the desired string length.
    // padString substitute string, not ideal, use this to complete.
    String.prototype.padEnd = function padEnd(targetLength,padString) {
        // Because >> is the operator, it is converted with Number. If it's NaN, it's converted to 0.
        // If a number is not converted to 0, it is returned with its original value.
        targetLength = targetLength>>0;
        // Check the padString argument passed in, returning a space string if not passed, or converting it to a string if passed.
        padString = String((typeofpadString ! = ='undefined' ? padString: ""));   // Space is a string of one length
        // If this(the current string) is already the desired length, return it without processing.
        if (this.length > targetLength) {
            return String(this);
        }
        else {
            // Check for a few characters missing.
            targetLength = targetLength - this.length;
            // If the ideal number of characters is greater than the alternate string, the alternate string is repeated.
            if (targetLength > padString.length) {
                // Count the number of times to repeat and add to the alternate string.
                padString += padString.repeat(targetLength/padString.length); 
            }
            // Concatenate the string, according to the previous calculation of several characters missing, truncate the substitute string.
            return String(this) + padString.slice(0,targetLength); }}; }Copy the code
"1".padEnd(3);
/ / "1"
Copy the code

When no second argument is passed, the default is a space string.

padStart()

Fills the current string header with the specified string until the specified length is reached. Returns a new string.

let hour = 9;
let min = 3;
let s = 45;
function format(time) {
    return String(time).padStart(2."0");
}
let time = `${format(hour)}:${format(min)}:${format(s)}`
/ / 09:03:45
Copy the code

repeat()

Specifies how many times a string is repeated to return a new string.

let str = "1";
str.repeat(4);
/ / "1111"
Copy the code

The length of the repeated string cannot exceed 1 << 28, because most browsers do not support this length.

slice()

Retrieves a portion of a string, returning a new string without changing the original string.

str.slice(beginIndex[, endIndex])
Copy the code

BeginIndex indicates the index position to start, and endIndex indicates the index bit to end.

The parameter supports negative numbers.

If the parameter is negative, strLength + beginIndex is processed. StrLength indicates the length of the string used to call the function.

let str = "1234";
str.slice(1.3);
/ / "23"
Copy the code

Starts at string index 1 and ends before index 3.

Essentially, it starts at index 1 and intercepts (3-1) characters.

str.slice(-2, -1);
/ / "3"
Copy the code

This is converted to str.slice((-2 + 4), (-1 + 4)), truncating (-1 – -2) characters starting from the penultimate.

str.slice(1, -1);
/ / "23"
Copy the code

Starts at index 1 and ends at the last character.

str.slice(2);
34 "/ /"
str.slice(2.100);
34 "/ /"
str.slice(2.1);
/ / ""
str.slice(2, -100);
/ / ""
Copy the code

If the endIndex endIndex does not have or exceeds the string length, the entire string is returned from the start index.

Returns an empty string if it is a nonlogical index.

str.slice(-100);
/ / "1234"
str.slice(-100.2);
/ / "12"
str.slice(-100, -100);
/ / ""
Copy the code

If beginIndex is negative, plus strLength is still negative, it goes to zero.

str.slice(NaN);
/ / "1234"
str.slice(null);
/ / "1234"
str.slice(true);
/ / "234"
str.slice("abc");
/ / "1234"
Copy the code

Both arguments passed in are transformed by calling Number(), or treated as 0 if NaN.

str.slice(0.1.1);
/ / "1"
str.slice(0."1.9");
/ / "1"
Copy the code

Is converted first to a numeric type and then to an integer type. I’m going to round down.

substring()

Similar to slice, it extracts a portion of a string and returns a new string, leaving the original string unchanged.

str.substring(indexStart[, indexEnd])
Copy the code

The argument does not support negative numbers, which are treated as 0.

Matters needing attention:

  • ifindexStartIs equal to theindexEnd.substringReturns an empty string.
  • If you omitindexEnd.substringExtract characters all the way to the end of the string.
  • If either parameter is less than 0 orNaN, isAs a 0.
  • If any parameter is greater thanstringName.lengthIs regarded asstringName.length.
  • ifindexStartIs greater thanindexEnd,substringThe execution effect is likeTranspose two parametersThe same. See the example below.
let str = "abcdefg";

/ / output "ABC"
str.substring(0.3);
str.substring(3.0);
str.substring(3, -3);
str.substring(3.NaN);
str.substring(-2.3);
str.substring(NaN.3);

/ / output efg ""
str.substring(4.7);
str.substring(7.4);

/ / output ""
str.substring(4.4);

/ / output "abcdef"
str.substring(0.6);

/ / output "abcdefg"
str.substring(0.7);
str.substring(0.10);
Copy the code

Arguments less than 0 and NaN are replaced by 0, and arguments greater than the length of the string are replaced by the length of the string, and the two arguments are compared, swapping their positions when the former argument is greater than the latter.

substr()

Slightly different from slice and Substring, the second parameter indicates the number of intercepts. Do not change the original string.

str.substr(start[, length])
Copy the code

Start indicates the index position to start from, and length indicates the number of characters to be cut back.

The first argument supports negative numbers.

If start is negative, it is treated as strLength + start.

Matters needing attention:

  • ifstartIs positive and is greater than or equal to the length of the stringsubstrReturns an empty string.
  • ifstartIs negative, thensubstrThink of it as a character index starting at the end of the string.
  • ifstartNegative andabs(start)Is greater than the length of the stringAs a 0To deal with.
  • iflengthIs 0 or negative, thensubstrReturns an empty string.
  • If you ignorelength,substrExtract characters up to the end of the string.
let str = "abcdefghij";

str.substr(1.2);   
// "bc"
str.substr(-3.2);  
// "hi"
str.substr(-3);  
// "hij"
str.substr(1);
// "bcdefghij"
str.substr(-20.2);
// "ab"
str.substr(20.2); 
/ / ""
Copy the code

toUpperCase()

Returns a string in all uppercase forms. Do not change the original string.

When you set its context this value to a non-string value, any non-string value is converted to a string.

const a = String.prototype.toUpperCase.call({
  toString: function toString() {
    return 'abcdef'; }});// "ABCDEF"
const b = String.prototype.toUpperCase.call(true);
// "TRUE"
Copy the code

toLowerCase()

In contrast to toUpperCase, return an all-lowercase string.

split()

Splits a string into arrays in the specified form.

let str = "6";
let arr = str.split(",");
// [1, 2, 3, 4, 5, 6]
Copy the code
let str = "123456";
str.split("");
/ / [6]
Copy the code

We just split each bit of the string into an array.

let str = "abcd";
str.split();
// ["acbd"]
Copy the code

No parameters are passed, or the parameters themselves are put into the array if they do not meet the requirements.

trim()

Remove whitespace characters from the left and right sides of the string.