首页 > web前端 > js教程 > 正文

JavaScript 中的字符串方法

王林
发布: 2024-08-14 20:53:32
原创
860 人浏览过

String methods in javascript

什么是字符串?

*用引号括起来的一个或多个字符的序列称为字符串。
*引号可以是单引号 '' 或双引号 " " 或反引号 ``.
并且,字符序列可以是字母、数字、符号等

字符串方法

1.charAt(索引)

*charAt() 返回字符串中指定索引处的字符。
*字符串的第一个字符的索引为 0,第二个字符的索引为 1,依此类推...

例子

let text = "HELLO";
让 char = text.charAt(0);
console.log(char)// 返回“H”

2.长度

*此属性返回字符串中的字符数。

例子

let text = "HELLO";
让长度 = text.length;
console.log(length) // 返回 5

3.切片(开始,结束)

*提取字符串的一部分并将其作为新字符串返回。起始索引是包含的,而结束索引是排除的。

例子

let text = "HELLO WORLD";
让部分 = text.slice(0, 5);
console.log(part) // 返回“HELLO”

4.子串(开始,结束)

*与 slice() 类似,但将负索引视为 0。它提取两个指定索引之间的字符。

例子

let text = "HELLO WORLD";
让部分 = text.substring(0, 5);
console.log(part)// 返回“HELLO”

5.toUpperCase()

*将字符串中的所有字符转换为大写。

例子

let text = "hello";
让 upper = text.toUpperCase();
console.log(upper)// 返回“HELLO”

6.toLowerCase()

*将字符串中的所有字符转换为小写。

例子

let text = "HELLO";
让 lower = text.toLowerCase();
console.log(lower)// 返回“hello”

7.修剪()

*删除字符串两端的空格。

例子

let text = " 你好";
让修剪 = text.trim();
console.log(trimmed) // 返回“hello”

8.concat()

*连接两个或多个字符串并返回一个新字符串。

例子

let text1 = "Hello";
让text2 =“世界”;
让组合 = text1.concat(" ", text2);
console.log(combined) // 返回“Hello World”

9.indexOf(子串)

*返回指定子字符串第一次出现的索引。如果没有找到则返回-1。

例子

let text = "HELLO WORLD";
让索引 = text.indexOf("O");
console.log(index)// 返回 4

10.替换(搜索值,新值)

*用新值替换第一次出现的指定值。

例子

let text = "HELLO WORLD";
let newText = text.replace("WORLD", "EVERYONE");
console.log(newText)// 返回“HELLO EVERYONE”

11.replaceAll(搜索值,新值)

*用新值替换所有出现的指定值。

例子

let text = "HELLO WORLD WORLD";
let newText = text.replaceAll("WORLD", "EVERYONE");
console.log(newText)// 返回“HELLO EVERYONE EVERYONE”

12.split(分隔符)

*根据指定的分隔符将字符串拆分为子字符串数组。

例子

let text = "HELLO WORLD";
让 parts = text.split(" ");
console.log(parts)// 返回 ["HELLO", "WORLD"]

13.连接(分隔符)

*使用指定的分隔符将数组的元素连接到字符串中。

例子

let array = ["HELLO", "WORLD"];
let join = array.join(" ");
console.log(joined)// 返回“HELLO WORLD”

14.startsWith(搜索字符串)

*检查字符串是否以指定字符串开头。

例子

let text = "HELLO WORLD";
让starts = text.startsWith("HELLO");
console.log(starts)// 返回 true

15.endsWith(搜索字符串)

*检查字符串是否以指定字符串结尾。

例子

let text = "HELLO WORLD";
让结束 = text.endsWith("WORLD");
console.log(ends)// 返回 true

16.includes(搜索字符串)

*检查字符串是否包含指定的子字符串。

例子

let text = "HELLO WORLD";
让includes = text.includes(“LO”);
console.log(includes)// 返回 true

以上是JavaScript 中的字符串方法的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!