Reason: When a computer processes a string, it first temporarily wraps the string as an instance of the string object, like `var str2 = new String(str1);`. This `str2` string object instance can then be used to invoke various methods, such as `str2.slice(3, 6);`. Afterward, the computer disposes of this temporarily wrapped `str2` by setting it to `null`.
Characteristics: All methods of string objects do not modify the original string itself; they only return a new string after the operation is complete.
Commonly Used String Properties and Methods in the Workplace:
- `.length` - String length
- `.charAt(index)` - Returns the character at the specified index.
- `.indexOf(x)` - Returns the first occurrence position of `x` in the original string; returns -1 if not found.
- `.concat()` - Concatenates strings.
- `.split("")` - Splits a string into an array of characters.
- `.toLowerCase()` - Converts all characters to lowercase.
- `.toUpperCase()` - Converts all characters to uppercase.
- `.slice(start, end)` - String slicing, extracts characters from `start` to `end`, where `start` is inclusive and `end` is exclusive.
- `.substr(start, numbers)` - String extraction, retrieves a substring of a specified length from the beginning.
- `.substring(start, end)` - String extraction, extracts characters from `start` to `end`, where `start` is inclusive and `end` is exclusive.
Difference between `slice` and `substring`:
const str = "Hello, World";
const sliced = str.slice(-5); // 返回 "World",从末尾开始提取
const substringed = str.substring(-5); // 返回 "Hello",负数索引被视为0
const str = "Hello, World";
const sliced = str.slice(0, 5); // 返回 "Hello"
const substringed = str.substring(0, 5); // 返回 "Hello"
原因 : 计算机工作时先将字符串进行一个临时包装 var str2 = new String(str1); 那么这个str2 字符串对象实例有很多方法可以调用, 比如str2.slice(3,6); 然后计算机再将临时包装的这个str2销毁 str2 = null;
特点:字符串对象的所有方法,都不会修改字符串本身,只会在操作完成后返回新的字符串。
工作中常用字符串属性和方法:
.length - 字符串长度
.chatAt(index) - 返回指定下标index位置的方法
.indexOf(x) - 在原始字符串中首次出现x的位置,没有返回-1
.concat() - 字符串拼接
.split("") - 分割字符串成一个数组[,,,,]
.toLowerCase() - 所有字符转小写
.toUpperCase() - 所有字符转大写
.slice(start,end) - 字符串截取,从start截取到end,左闭右开
.substr(start,numbers) - 字符串截取,从开始位置截取到指定长度字符串
.substring(start,end) - 字符串截取,从start截取到end,左闭右开
slice与substring区别:
const str = "Hello, World";
const sliced = str.slice(0, 5); // 返回 "Hello"
const substringed = str.substring(0, 5); // 返回 "Hello"
const str = "Hello, World";
const sliced = str.slice(-5); // 返回 "World",从末尾开始提取
const substringed = str.substring(-5); // 返回 "Hello",负数索引被视为0