js 字符串常用方法和示例

253 阅读3分钟

JS 字符串方法可以分为以下几类:增加、截取、修改、查找、分割、字符串匹配等。本文将对这些方法进行分类介绍,并附上示例代码:

1. 增加字符串内容

concat()

作用concat() 方法用于将一个或多个字符串拼接成一个新字符串。

示例

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

2. 截取字符串

在 JavaScript 中,有三种常用方法可以用于截取字符串:slice()substring()substr()。它们的用法略有不同,但都可以根据传入的起始和结束位置的索引来截取一段字符串。

slice()

作用:根据指定的起始索引和结束索引(不包括结束索引)截取字符串,并返回新字符串。

substring()

作用:类似于 slice(),但不接受负数索引。

startsWith()

作用:检测字符串是否以某些元素开头的,返回 true 和 false。

示例

let stringValue = "hello world";
console.log(stringValue.slice(3));        // "lo world"
console.log(stringValue.substring(3));    // "lo world"
console.log(stringValue.startsWith('hel'));       // true
console.log(stringValue.slice(3, 7));     // "lo w"
console.log(stringValue.substring(3, 7)); // "lo w"
console.log(stringValue.substr(3, 7));    // "lo worl"

3. 修改字符串

trim()

作用trim() 方法用于去除字符串两端的空白字符。

toLowerCase()toUpperCase()

作用toLowerCase() 将字符串转换为小写,toUpperCase() 将字符串转换为大写。

示例

let str = "  Hello World!  ";
console.log(str.trim());            // "Hello World!"
console.log(str.toLowerCase());     // "hello world!"
console.log(str.toUpperCase());     // "HELLO WORLD!"

4. 查找字符串内容

charAt(index)

作用charAt() 方法根据传入的索引,返回字符串中对应位置的字符。

indexOf(searchValue)

作用indexOf() 方法用于查找字符串中某个子字符串的首次出现位置,找到了返回索引,没找到返回 -1

includes(searchString, position)

作用includes() 方法判断字符串是否包含指定的子字符串,返回 truefalse

示例

let message = "abcde";
console.log(message.charAt(2)); // "c"

let stringValue = "hello world";
console.log(stringValue.indexOf("o")); // 4
console.log(stringValue.includes("world")); // true
console.log(stringValue.includes("World")); // false

5. 分割字符串

split(separator, limit)

作用split() 方法根据指定的分隔符,将字符串拆分成一个数组。

示例

let str = "12+23+34";
let arr = str.split("+");
console.log(arr); // ["12", "23", "34"]

6. 字符串匹配与替换

JavaScript 提供了一些方法用于匹配和替换字符串中的内容,这些方法通常结合正则表达式使用。

match(regexp)

作用match() 方法用于匹配字符串中的内容,返回一个数组或 null

search(regexp)

作用search() 方法用于搜索字符串中符合正则表达式的内容,返回匹配项的索引,未找到则返回 -1

replace(searchValue, newValue)

作用replace() 方法用于替换字符串中的指定内容,并返回新的字符串。

示例

let text = "cat, bat, sat, fat";
let pattern = /.at/;

// match
let matches = text.match(pattern);
console.log(matches[0]); // "cat"

// search
let pos = text.search(/at/);
console.log(pos); // 1

// replace
let result = text.replace("at", "ond");
console.log(result); // "cond, bat, sat, fat"

总结

本文介绍了 JavaScript 中常用的字符串方法,并将其归类为增加、截取、修改、查找、分割和匹配替换。熟练掌握这些方法,可以让你在处理字符串时更加得心应手,提高代码的可读性和维护性。希望这些内容对你在日常开发中有所帮助。