返回

JavaScript 字符串的属性和方法汇总

前端

JavaScript 字符串的属性

1. length

length 属性返回字符串的长度。

const str = "Hello World";
console.log(str.length); // 11

2. indexOf()

indexOf() 方法返回指定子字符串在字符串中第一次出现的位置。如果未找到子字符串,则返回 -1。

const str = "Hello World";
console.log(str.indexOf("World")); // 6

3. lastIndexOf()

lastIndexOf() 方法返回指定子字符串在字符串中最后一次出现的位置。如果未找到子字符串,则返回 -1。

const str = "Hello World";
console.log(str.lastIndexOf("World")); // 6

4. slice()

slice() 方法返回从指定位置开始到指定位置结束的新字符串。

const str = "Hello World";
console.log(str.slice(6)); // "World"
console.log(str.slice(2, 7)); // "llo W"

5. substring()

substring() 方法返回从指定位置开始到指定位置结束的新字符串。与 slice() 方法不同的是,substring() 方法不会接受负数索引。

const str = "Hello World";
console.log(str.substring(6)); // "World"
console.log(str.substring(2, 7)); // "llo W"

6. substr()

substr() 方法返回从指定位置开始的指定长度的新字符串。

const str = "Hello World";
console.log(str.substr(6)); // "World"
console.log(str.substr(2, 3)); // "llo"

JavaScript 字符串的方法

1. replace()

replace() 方法将字符串中的指定子字符串替换为另一个子字符串。

const str = "Hello World";
console.log(str.replace("World", "Universe")); // "Hello Universe"

2. toUpperCase()

toUpperCase() 方法将字符串中的所有字母转换为大写。

const str = "Hello World";
console.log(str.toUpperCase()); // "HELLO WORLD"

3. toLowerCase()

toLowerCase() 方法将字符串中的所有字母转换为小写。

const str = "Hello World";
console.log(str.toLowerCase()); // "hello world"

4. trim()

trim() 方法从字符串的两端删除所有空白字符。

const str = "  Hello World  ";
console.log(str.trim()); // "Hello World"

5. padStart()

padStart() 方法在字符串的开头填充指定数量的字符。

const str = "World";
console.log(str.padStart(10, "*")); // "**** ***World"

6. padEnd()

padEnd() 方法在字符串的末尾填充指定数量的字符。

const str = "Hello";
console.log(str.padEnd(10, "*")); // "Hello**** **"

7. includes()

includes() 方法检查字符串是否包含指定的子字符串。

const str = "Hello World";
console.log(str.includes("World")); // true

8. startsWith()

startsWith() 方法检查字符串是否以指定的子字符串开头。

const str = "Hello World";
console.log(str.startsWith("Hello")); // true

9. endsWith()

endsWith() 方法检查字符串是否以指定的子字符串结尾。

const str = "Hello World";
console.log(str.endsWith("World")); // true

10. repeat()

repeat() 方法将字符串重复指定次数。

const str = "Hello";
console.log(str.repeat(3)); // "HelloHelloHello"

结语

本文对 JavaScript 字符串的属性和方法进行了全面汇总。希望本文能够帮助开发者更好地理解和使用 JavaScript 字符串。