当前位置: 首页> 新闻> 焦点 > js字符串常用方法

js字符串常用方法

时间:2025/7/8 21:25:56来源:https://blog.csdn.net/m0_75276704/article/details/141810939 浏览次数:0次

1.length

获取字符串长度

let str = "Hello";
console.log(str.length); // 输出 5

2.trim

去掉字符串两端空白

let str = "   Hello World   ";
console.log(str.trim()); // 输出 "Hello World"

3.includes

检查字符串是否包含某个子字符串,返回布尔值。

let str = "Hello World";
console.log(str.includes("World")); // 输出 true
console.log(str.includes("world")); // 输出 false

4.charAt

获取指定索引位置的字符

let str = "Hello";
console.log(str.charAt(0)); // 输出 H

5.concat

连接多个字符串。

let str1 = "Hello";
let str2 = "World";
let result = str1.concat(" ", str2);
console.log(result); // 输出 Hello World

6.indexOf

查找子字符串首次出现的位置,如果未找到返回 -1。

let str = "Hello World";
console.log(str.indexOf("World")); // 输出 6
console.log(str.indexOf("world")); // 输出 -1

7.lastIndexOf

查找子字符串最后一次出现的位置,如果未找到返回 -1。

let str = "Hello World World";
console.log(str.lastIndexOf("World")); // 输出 12

8.toUpperCase

转为大写

let str = "hello";
console.log(str.toUpperCase()); // 输出 HELLO

9.toLowerCase

转为小写

let str = "HELLO";
console.log(str.toLowerCase()); // 输出 hello

10.substr(start,length)

从指定位置开始截取指定长度的字符串

let str = "Hello World";
console.log(str.substr(0, 5)); // 输出 Hello
console.log(str.substr(6, 5)); // 输出 World

11.substring(start,end)

截取字符串的一部分

let str = "Hello World";
console.log(str.substring(0, 5)); // 输出 Hello
console.log(str.substring(6)); // 输出 World

12.split

字符串转数组

let str = "Hello,World,This,Is,A,Test";
console.log(str.split(",")); // 输出 ["Hello", "World", "This", "Is", "A", "Test"]
console.log(str.split(",", 3)); // 输出 ["Hello", "World", "This,Is,A,Test"]

13.replace

替换字符串中的指定值

let str = "Hello World";
console.log(str.replace("World", "Universe")); // 输出 Hello Universe

关键字:js字符串常用方法

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: