JavaScript 字符串方法详解 - 全面解析常用字符串操作
JavaScript 常用字符串方法详解
本文将深入讲解 JavaScript 中常见的字符串方法,帮助你更好地理解和运用它们。
- length(): 返回字符串的长度。
const str = 'Hello world!';
console.log(str.length); // 输出:12
- charAt(index): 返回字符串中指定位置的字符。
const str = 'Hello world!';
console.log(str.charAt(0)); // 输出:'H'
- concat(str1, str2, ...): 连接两个或多个字符串。
const str1 = 'Hello';
const str2 = ' ';
const str3 = 'world!';
console.log(str1.concat(str2, str3)); // 输出:'Hello world!'
- indexOf(searchValue, fromIndex): 返回字符串中第一次出现指定值的索引位置,从指定的位置开始搜索。
const str = 'Hello world!';
console.log(str.indexOf('world')); // 输出:6
console.log(str.indexOf('world', 7)); // 输出:-1
- lastIndexOf(searchValue, fromIndex): 返回字符串中最后一次出现指定值的索引位置,从指定的位置开始搜索。
const str = 'Hello world! world!';
console.log(str.lastIndexOf('world')); // 输出:12
console.log(str.lastIndexOf('world', 11)); // 输出:6
- slice(startIndex, endIndex): 提取字符串中的一部分,并返回新字符串。startIndex 和 endIndex 分别指定开始和结束位置。
const str = 'Hello world!';
console.log(str.slice(0, 5)); // 输出:'Hello'
console.log(str.slice(6)); // 输出:'world!'
- substring(startIndex, endIndex): 与 slice() 方法类似,但不接受负数参数。
const str = 'Hello world!';
console.log(str.substring(0, 5)); // 输出:'Hello'
console.log(str.substring(6)); // 输出:'world!'
- substr(startIndex, length): 与 slice() 方法类似,但第二个参数指定要提取的字符数。
const str = 'Hello world!';
console.log(str.substr(0, 5)); // 输出:'Hello'
console.log(str.substr(6, 5)); // 输出:'world'
- replace(searchValue, replaceValue): 替换字符串中的指定值为新值。
const str = 'Hello world!';
console.log(str.replace('world', 'JavaScript')); // 输出:'Hello JavaScript!'
- toLowerCase(): 将字符串转换为小写。
const str = 'Hello World!';
console.log(str.toLowerCase()); // 输出:'hello world!'
- toUpperCase(): 将字符串转换为大写。
const str = 'Hello World!';
console.log(str.toUpperCase()); // 输出:'HELLO WORLD!'
- trim(): 删除字符串两端的空格。
const str = ' Hello world! ';
console.log(str.trim()); // 输出:'Hello world!'
- split(separator, limit): 将字符串分割成数组,separator 指定分隔符,limit 指定数组的最大长度。
const str = 'Hello, world!';
console.log(str.split(',')); // 输出:['Hello', ' world!']
console.log(str.split(' ', 1)); // 输出:['Hello,']
通过以上示例,你应该对 JavaScript 中常用的字符串方法有了更深的理解,可以根据实际需求灵活运用它们来操作字符串。
原文地址: https://www.cveoy.top/t/topic/jzWd 著作权归作者所有。请勿转载和采集!