JavaScript字符串有很多内置方法,以下是其中一些常用的方法:
length
length属性返回字符串的长度,即包含多少个字符。例如:
let str = 'hello';
console.log(str.length); // 5
charAt
charAt方法返回指定索引处的字符。例如:
let str = 'hello';
console.log(str.charAt(0)); // "h"
console.log(str.charAt(1)); // "e"
concat
concat方法将两个或多个字符串连接起来,返回一个新的字符串。例如:
let str1 = 'hello';
let str2 = 'world';
console.log(str1.concat(' ', str2)); // "hello world"
indexOf
indexOf方法返回指定字符或子字符串在字符串中第一次出现的位置,如果没有找到则返回-1。例如:
let str = 'hello world';
console.log(str.indexOf('o')); // 4
console.log(str.indexOf('world')); // 6
lastIndexOf
lastIndexOf方法返回指定字符或子字符串在字符串中最后一次出现的位置,如果没有找到则返回-1。例如:
let str = 'hello world';
console.log(str.lastIndexOf('o')); // 7
console.log(str.lastIndexOf('world')); // 6
slice
slice方法返回字符串的一个子串,可以指定起始位置和结束位置。例如:
let str = 'hello world';
console.log(str.slice(0, 5)); // "hello"
console.log(str.slice(6)); // "world"
substring
substring方法返回字符串的一个子串,可以指定起始位置和结束位置,与slice方法类似。不同之处在于,如果指定的起始位置大于结束位置,则会自动交换这两个位置。例如:
let str = 'hello world';
console.log(str.substring(0, 5)); // "hello"
console.log(str.substring(6)); // "world"
replace
replace方法用一个新字符串替换原字符串中的某个子串,返回替换后的新字符串。例如:
let str = 'hello world';
console.log(str.replace('world', 'javascript')); // "hello javascript"
toUpperCase
toUpperCase方法将字符串中所有的字符都转换为大写字母,返回一个新字符串。例如:
let str = 'hello world';
console.log(str.toUpperCase()); // "HELLO WORLD"
toLowerCase
toLowerCase方法将字符串中所有的字符都转换为小写字母,返回一个新字符串。例如:
let str = 'HELLO WORLD';
console.log(str.toLowerCase()); // "hello world"
以上这些方法只是JavaScript字符串方法的一小部分,JavaScript还提供了许多其他有用的方法,可以根据需求选择使用。