SoFunction
Updated on 2025-04-04

Summary of the usage of string-related methods in JavaScript

The string in JavaScript is from16-bit code unitcomposition. Generally speaking, a character = 16-bit symbol, and this type of character is also calledSingle symbol characters. Another character composition strategy isAgent pair, It consists of two pairs of 16-bit symbols, that is, one character corresponds to two 16-bit symbols, used to supplement characters.

JavaScript uses two strategies to mix Unicode encodings:USC-2andUTF-16

Understand character encoding

  1. The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)
  2. JavaScript’s Internal Character Encoding:UCS-2 or UTF-16?

The original string value can call methods of all String objects; there are 3 inherited methods: valueOf(), toLocaleString(), and toString(), which all return the original string value of the string object; there is 1 length attribute, whose value is the number of characters contained in the string.

The following describes the related methods of JavaScript strings.

No changes to the original string without explanation.

、charCodeAt、codePointAt

charAt gets the character specified position. charCodeAt gets the encoding of the character specified position (hexadecimal to decimal).

const str="Hello, the world!";
((0)); //H
((7)); //boundary((0)); //72
((7)); //30028
(parseInt(30028).toString(16)); //754c

charCodeAt is only suitable for single symbol characters, while the proxy needs to use codePointAt for characters.

To correctly parse strings containing both single symbol characters and proxy pairs, use codePointAt to receive the index of the 16-bit symbol and return the index positionCode points(The complete identification of a character in Unicode).

const str = "ab😂ba";
((2)); // 55357
((2)); // 128514

、fromCodePoint

fromCharCode is used to create characters based on a given UTF-16 symbol, and can accept multiple values ​​and generate a string. fromCodePoint creates characters with a given code point, and can also accept multiple values ​​to generate a string.

// Create characters using fromCharCode()const char1 = (65); // 65 is the UTF-16 code element of the character 'A'(char1); // Output: A// Create characters using fromCodePoint()const char2 = (128514); // 128514 is the code point of the smiley face symbol(char2); // Output:😂

Are two identical characters necessarily equal? If these two characters look the same, but the corresponding characters are encoded differently, then they are not equal, for example

const char1 = 'A';   // Latin letter capital Aconst char2 = 'Α';  // Greek letters capital alpha// Compare whether two characters are equal(char1 === char2); // Output: false, although the appearance is similar, the character encoding is different// Get character encoding((0)); // Output: 65, Unicode encoding of character A((0)); // Output:913,characterΑofUnicodecoding

concat is used to splice strings, which can splice multiple strings at once. Of course, we use the + sign more often to splice strings.

let str="Hello "
(("World","!")) //"Hello World!"
(str) //"Hello"

、substring、substr

These three methods are similar, but also have significant differences, so please see below.

They are all used to extract substrings, both accept 1 or 2 parameters, and the first parameter is an index of the starting position. If the second parameter is omitted, it means that it is intercepted to the end of the string. The difference is that the second parameter of slice and substring is the index of the end position (the intercepted part does not include the end position), while the second parameter of substr is the number of characters that intercept the string from the start position. It is worth noting that substring will take a smaller number as the starting position, and the first parameter may be larger than the second parameter.

For negative parameters, slice will add all string lengths (that is, count from right to left) until it is a positive number; substr will participate in the first negative part of the string length and turn the second negative parameter to 0; substring will convert all negative parameters to 0.

let str = "Hello world!"
((0)) //Hello world!
((0, 5)) //Hello
((0)) //Hello world!
((0, 5)) //Hello
((0)) //Hello world!
((0, 5)) //Hello
((-5)) //orld!
((-5)) //Hello world!
((-5)) //orld!
((0, -5)) //Hello w
((0, -5)) //Empty string((0, -5)) //Empty string((-5, -2)) //orl
((-5, -2)) //Empty string((-5, -2)) //Empty string((-2, -5)) //Empty string((-2, -5)) //Empty string((-2, -5)) //Empty string((5, 0)) //Empty string((5, 0)) //Hello
((5, 0)) //Empty string

and lastIndexOf

The previous article has introduced the method of obtaining strings based on location. We can also obtain its locations based on strings - indexOf and lastIndexOf. The difference is that indexOf is searched from front to back, while lastIndexOf is searched from back to front. If not found, return -1. These two methods can accept the second parameter, indicating the starting search position.

、endsWith、includes

startsWith, endsWith, and include are methods to determine whether a certain string is contained, returning a boolean value.

include check the entire string.

startsWith and endsWith match whether there are incoming strings at the beginning and end respectively.

startsWith and include both accept the second parameter, indicating the starting search position.

、trimLeft、trimRight

The trim method deletes all spaces before and after the string. trimLeft and trimRight respectively delete the space on the left side of the string and the space on the right side of the string.

The repeat method accepts an integer as a parameter, indicating the number of times the string is copied, and then returns the string they are spliced ​​together.

、padEnd

pad - fill.

padStart and padEnd are respectively filled with specified strings of specified length before and after the string. The first parameter is the length to which the string should be filled after filling, and the second parameter is the string to be filled.

let str = "Hello"
((10, "World")) //WorldHello
((10, "World")) //HelloWorld

、toLocaleLowerCase、toUpperCase、toLocaleUpperCase

toLowerCase is used to convert all characters in a string to lowercase. It is not affected by geographic settings and simply converts characters to lowercase. toLocaleLowerCase() is different in that it is affected by the geographic setting and may convert certain specific characters to lowercase according to the current locale setting.

toUpperCase and toLocaleUpperCase are the same as above.

11. Pattern matching related methods

The first one is match, which is essentially the same as RegExp's exec method, returning an array form of matching results. If you use the global pattern g, it returns an array of all matching results, otherwise it returns an array where the first element is the matching string and the subsequent element is the capture group in the regular expression.

let str = "To be what we are, and to become what we are capable of becoming, is the only end of life."
// Use match to match all words containing alet reg1 = /\b[a-zA-Z]*a[a-zA-Z]*\b/g
((reg1)) // [ 'what', 'are', 'and', 'what', 'are', 'capable' ]
// Use match to match words containing a, without using global matchlet reg2 = /\b[a-zA-Z]*a[a-zA-Z]*\b/
((reg2))
// [
//   'what',
//   index: 6,
//   input: 'To be what we are, and to become what we are capable of becoming, is the only end of life.',
//   groups: undefined
// ]

The second is search, which returns the matching index position, and returns -1 if there is no match.

let str = "To be what we are, and to become what we are capable of becoming, is the only end of life."
// Use search to match welet reg = /we/g
((reg)) // 11

The third is replace, which replaces the contents matched by the regular expression with a new string or function.

const originalString = "Hello, world! Hello, universe!";
// Replace a single match in a stringconst replacedString1 = ("world", "friends");
(replacedString1); // Output: Hello, friends! Hello, universe!// Use regular expressions to replace (replace only the first match)const replacedString2 = (/Hello/, "Hi");
(replacedString2); // Output: Hi, world! Hello, universe!// Use regular expressions to replace (replace all matches)const replacedString3 = (/Hello/g, "Hi");
(replacedString3); // Output: Hi, world! Hi, universe!// Use $1, $2, $3, $4, etc. to replace the matchconst replacedString4 = (/(Hello), (world)! (Hello), (universe)!/g, "$3, $4! $1, $2!");
(replacedString4); // Output: Hello, universe! Hello, world!// Use functions to replace matchesconst replacedString5 = (/(Hello), (world)! (Hello), (universe)!/g, 
function (matched, p1, p2, p3, p4, offset, original) {
    (matched) // Matched string    (offset) // The offset of the matching string in the original string    (original) // Original string    return p3 + ", " + p4 + "! " + p1 + ", " + p2 + "!";
}
);
(replacedString5); // Output:Hello, universe! Hello, world!

The last one is split, which divides the string into an array based on the passed delimiter, which can be a string or a RegExp object.

const str="apple,banana,orange"
//Use commas as separator((",")) //["apple","banana","orange"]
//Quantitize array size((",",2)) //["apple","banana"]
//Use regular expressionconst text="apple   orange\tbanana"
const parts=(/\s+/) //Match continuous spaces(parts) //["apple","orange","banana"]

12. Iteration method

The @@iterator method is exposed on the prototype of the string

const str = "abc"
const str2 = str[]()
(()) //{ value: 'a', done: false }
(()) //{ value: 'b', done: false }
(()) //{ value: 'c', done: false }
(()) //{ value: undefined, done: true }

With this iterator, we use for-of to iterate over the string, and structure the string using the deconstructed operator.

localeCompare compares strings and string parameters before and after the order of the alphabet. If the string is before the string parameter, it returns a negative value; if it is equal, it returns 0; if the string is behind the string parameter, it returns a positive value.

This is the end of this article about the summary of the usage of string-related methods in JavaScript. For more related JavaScript string content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!