JavaScript Advanced Programming -- String type

The common primitive types of ECMAScript are String type. We can declare a String directly through literal quantity

var str = 'hello world!'
str.length //12
str.charAt(2) //l

The original type of data itself is not an object, so there should be no properties and methods, but the original value of String type can refer to some methods

It can be found that the declared string variable str can normally call some methods. These two methods are accessed in the way of reading. Generally, when accessing the string in the way of reading, the background will automatically perform the following three steps:

  • Create an instance of String type

  • Call a specific method on an instance

  • Destroy instance

    The str.charAt(2) runtime actually performs the following actions:

    var str = new String('hello world!');
    str.indexOf(2); //l
    str = null;
    

This behavior allows the original value to have the behavior of the object. There are the same wrapper types (Boolean and Number) for Boolean and numeric values
All methods of the String object can be called on the original value of the String.

Common methods of String objects

characters finding

charAt()

Returns the character at the specified index position

var str = new String('hello world!');
//charAt() does not pass parameters. The default index value is 0, which returns the character value of the first bit
str.charAt()//"h"
//Returns the character with the specified index value of 3
str.charAt(3)//"l"

//Returns a null character outside the index range
str.charAt(-6)//""
str.charAt(15)//""

charCodeAt()

Returns the character encoding of the specified index position

var str = new String('hello world!');

//charCodeAt() does not pass parameters. The default is 0 index value, that is, it returns the character encoding of the first bit
str.charCodeAt()//104
//Returns the character encoding with the specified index value of 3
str.charCodeAt(3)//108

//NaN not in index range
str.charCodeAt(-6)//NaN
str.charCodeAt(15)//NaN

fromCharCode()

Creates a character in a string based on the specified symbol

var str = String.fromCharCode(104,108,97)//"hla"

String operation method

concat()

Splices one or more strings into a new string

var str1 = 'hello ';
//concat can pass multiple parameters, that is, multiple strings can be spliced at a time
var str2 = str1.concat('world','!'); //"hello world!"

Is it more convenient to use the plus sign operator (+) to splice strings

slice()

Pass two parameters: the start position of the extracted string and the optional end position of the extracted string

var str = 'hello world!'
str.length //12
//The entire string is extracted by default without passing parameters
str.slice() //"hello world!"
//When a parameter is used, the default is the start extraction position and the end position is the length of the string (extracted to the end of the string)
str.slice(6)//"world!"
//Two parameters to extract the string whose index value is greater than or equal to 0 and less than 6)
str.slice(0,6)//"hello "
//Automatically omit out of range extraction
str.slice(6,15)//"world!"
//If the parameter value is negative, convert all values into string length plus negative value, and extract the string with index value greater than or equal to 0 and less than 4
str.slice(0,-8) "hell"
//Extract a string whose index value is greater than or equal to 6 and less than 8
str.slice(-6,-4)//"wo"
//The index value is reversed (8,6) and returns null
str.slice(-4,-6)//""


substring()

Pass two parameters: the start position of the extracted string and the optional end position of the extracted string

Difference between substring() and slice:
When the parameter is negative, the subString() method converts all negative parameter values to 0
When the parameter value is reversed, it will be automatically converted to the one with small value as the starting position

var str = 'hello world!'
str.length //12
//The entire string is extracted by default without passing parameters
str.substring() //"hello world!"
//When a parameter is used, the default is the start extraction position and the end position is the length of the string (extracted to the end of the string)
str.substring(6)//"world!"
//Two parameters to extract the string whose index value is greater than or equal to 0 and less than 6)
str.substring(0,6)//"hello "
//Automatically omit out of range extraction
str.substring(6,15)//"world!"
//All negative parameter values are converted to 0, and the string with index value greater than or equal to 0 and less than 0 is extracted
str.substring(-6,-4)//""
//Extract a string whose index value is greater than or equal to 0 and less than 8
str.substring(-6,8)//"hello wo"
//When the parameter value is reversed, it will be automatically converted, and the small value will be used as the starting position
//Extract a string whose index value is greater than or equal to 0 and less than 2
str.substring(2,-8)//"he"
//Extract a string whose index value is greater than or equal to 1 and less than 4
str.substring(4,1)//"ell"

substr()

Two parameters are passed: the starting position of the extraction and the number of optional extraction substrings

substr() takes the first negative parameter value as a string length plus a negative value, and converts the second negative parameter value to 0

var str = 'hello world!'
str.length //12
//The entire string is extracted by default without passing parameters
str.substr() //"hello world!"
//When a parameter is used, the default is the start extraction position and the end position is the length of the string (extracted to the end of the string)
str.substr(6) //"world!"
//Two parameters, starting from the index value greater than or equal to 0, followed by 6 substrings)
str.substr(0,6) //"hello "
//Automatically omit out of range extraction
str.substr(6,15) //"world!"
//The extraction starts with the index value 6, followed by 0 characters (as long as the second parameter value is negative, the final result is an empty string)
str.substr(-6,-4) //""
//The extraction of index value starts with 6, followed by 3 characters
str.substr(-6,3) //"wor"

String position method

indexOf() and lastIndexOf() return the position of the substring (return - 1 if not found)

Pass two parameters: the substring of the search and the optional starting position of the search

indexOf()

Find substrings backwards from the beginning of a string

var str = 'hello world!';
//Pass a parameter to start searching from the beginning of the string by default
str.indexOf('llo') //2
//Pass two parameters to specify the index location to start the search
str.indexOf('l',1) //2
str.indexOf('l',4)//9
//When the search position of the second parameter is negative, the default is to search from the start position
str.indexOf('o',-2)//4
//Return - 1 not found
str.indexOf('ee')//-1

lastIndexOf()

Find substring forward from end of string

var str = 'hello world!';
//Pass a parameter. By default, look forward from the end of the string
str.lastIndexOf('o')
//Pass two parameters to specify the index position to look forward
str.lastIndexOf('o',8)//7
str.lastIndexOf('o',6)//4
//Negative number returns - 1
str.lastIndexOf('o',-1)//-1

String containing method

The method used to determine whether a string contains another string, which returns a Boolean value

startsWith()

Check for matches at the start of the index

Pass two parameters: the substring of the judgment and the starting position of the matching in the optional string

var str = 'hello world!';
//Whether str string starts with 'hello' string
str.startsWith('hello')//true
//Whether str string starts with 'llo' string
str.startsWith('llo')//false
//Modify the position of starting matching through the second parameter
str.startsWith('llo',2)//true

endsWith()

Check for matches starting at the end of the index

Pass two parameters: the substring of the judgment and the optional position as the end of the string

var str = 'hello world!';
//Whether str string starts with'd! ' End of string
str.endsWith('d!')//true
//Whether str string ends with 'rld' string
str.endsWith('rld');//false
//Modify the position of the end of the string through the second parameter
str.endsWith('rld',11);//true

includes()

Check the entire string

Pass two parameters: the substring of the judgment and the starting position of the matching in the optional string

var str = 'hello world!';
//Whether the str string contains' llo ', search from the beginning of the string
str.includes('llo') //true
//Pass two parameters to modify the location of the lookup
str.includes('llo',3)//false
//If it is not found in the whole string, false is returned
str.includes('eee')//false

trim() method

Clear the space before and after the string (does not affect the original value)

var str = ' hello ';
str.length//7
var str1 = str.trim();//'hello'
console.log(str1.length) //5


//The trimLeft and trimlight methods are used to clear the spaces at the beginning and end of the string, respectively
console.log(str.trimLeft())//'hello '
console.log(str.trimRight())//' hello'

repeat() method

Pass an integer parameter indicating how many times the string is copied

var str = 'hh ';
str.repeat(5)//"hh hh hh hh hh "

padStart() and padEnd() methods

padStart() fills the specified character or string in front of the string

Pass two parameters: length and optional padding character or string (default padding is empty)

var str = 'foo'
//If the specified length is less than or equal to the string length, the original string is returned
console.log(str.padStart(2)) //"foo"

//Do not pass the second parameter, and fill in spaces in front by default
console.log(str.padStart(6)) //"   foo"

//The specified length is 6, which is not enough. The default front filling is
console.log(str.padStart(6,'.')) //"...foo"

//If the specified length is 6, fill 'barr' in front, and the excess part will be omitted automatically
console.log(str.padStart(6,'barr')) //"barfoo"

padEnd() fills the specified character or string after the string

Pass parameters: length and optional padding characters or strings (the default padding value is empty)

var str = 'foo'
//Do not pass the second parameter, and fill in spaces after it by default
str.padEnd(6) //"foo   "
//The specified length is 6, which is not enough to fill in after
str.padEnd(6,'.')//"foo..."
//Specify a length of 6, fill in 'barr' after the string, and the excess part will be omitted automatically
str.padEnd(6,'barr') //"foobar"

String iteration and structure

A @ @ iterator method is exposed on the string prototype, indicating that each character of the string can be iterated.

Using for of can easily traverse each character

var str = 'hello';
for(const c of str) {
	console.log(c) // h e l l o
}

With this iterator, the string can be deconstructed by the deconstruction operator.

var str = 'hello';
var arr = [...str] //["h", "e", "l", "l", "o"]

Convert string case

Methods for converting strings to uppercase: toUpperCase() and toLocaleUpperCase()

var str = 'Hello';
console.log(str.toUpperCase())//HELLO
console.log(str.toLocaleUpperCase())//HELLO

Methods to convert strings to lowercase: toLowerCase() and toLocaleLowerCase()

var str = 'Hello';
console.log(str.toLowerCase())//hello
console.log(str.toLocaleLowerCase()) //hello

toLocaleUpperCase() and toLocaleLowerCase() are implemented on a locale specific basis.

localeCompare() method

Compare two strings

  • In alphabetical order, if the string should be in front of the string parameter, a negative value (generally - 1) is returned
  • Equal, return 0
  • In alphabetical order, if the string should be placed after the string parameter, a positive value (usually 1) is returned
var str = 'yellow'
str.localeCompare('blue') //1
str.localeCompare('yello') //0
str.localeCompare('zoo') //-1

Keywords: Javascript ECMAScript

Added by pankirk on Mon, 31 Jan 2022 03:24:46 +0200