js中的字符串方法总结

77 阅读1分钟

let stringValue = "hello world"

1、读取字符方法
console.log(stringValue.chartAt(1))
console.log(stringValue.chartCodeAt(1))
console.log(stringValue[1])

2、字符串操作方法(创建新字符串)
let result = stringValue.concat("!")
               = stringValue + "!"

slice()(推荐) substring() substr()

方法参数定义是否支持负索引是否自动交换参数
slice()(推荐)(start, end)✅支持​​负数索引​​(从末尾倒数)
substring()(start, end)不支持负数索引​​(负数会被视为 0)✅自动交换 start 和 end 如果 start > end
substr()(已废弃)(start, length)

3、字符串位置方法 indexOf() lastIndexOf()

4、trim() trimLeft() trimRight()

5、字符串大小写转换方法 toLowerCase() toLocaleLowerCase() toUpperCase() toLocaleUpperCase()

6、字符串的模拟匹配方法

match(),本质上与调用RegExp的exec()方法相同;

const str = "2023 and 2024"; 
const result = str.match(/\d+/g);// 全局匹配所有数字
console.log(result); // 输出: ["2023", "2024"](无分组信息)

search()

const str = "Hello, 2023!"; 
const index = str.search(/\d+/); // 查找数字 
console.log(index); // 7(数字 "2023" 的起始索引)

replace()

let str = "Hello World";
let newStr = str.replace("World", "JavaScript");
console.log(newStr); // "Hello JavaScript"

7、split()

 str.split(separator, limit);
separator(可选):指定分割字符串的模式,可以是字符串或正则表达式
limit(可选):限制返回数组的最大长度

8、localeCompare()

str.localeCompare(compareString[, locales[, options]])
"apple".localeCompare("banana"); // 返回负数("apple""banana" 前)
"banana".localeCompare("apple"); // 返回正数("banana""apple" 后)
"apple".localeCompare("apple");  // 返回 0(相等)

9、fromChartCode()

// 支持多个参数
const str = String.fromCharCode(72, 69, 76, 76, 79);
console.log(str); // "HELLO"

10、includes

let str = "Hello, world!";

console.log(str.includes("Hello")); // true
console.log(str.includes("hello")); // false(区分大小写)
console.log(str.includes("world", 8)); // true(从索引8开始搜索)