JS中常用字符串API - 使用汇总

前言

JavaScript 中有很多字符串(String)API 可以用来操作和处理字符串,下面列举一些常用的:

1. length

获取字符串长度。

const str = "hello world!";
console.log(str.length);   // 12

2. charAt() 方法

返回指定位置的字符。

//返回字符串中的第二个字符
var str = "hello";
var n = str.charAt(1)
console.log(n) // e

3. indexOf / lastIndexOf

返回字符串中特定子串第一次出现时的索引或最后一次出现时的索引。找不到返回 -1

const str = "hello world!";
console.log(str.indexOf("l"));         // 2
console.log(str.lastIndexOf("l"));     // 9

4. substr / substring / slice

从原始字符串中 截取 一个子串并返回。
其中 slice字符串 和 数组 上都能使用。

1)substr() 、substring() 、slice() 都是截取字符串。slice()也可截取数组。
2)substr() 第一个参数是开始位置,第二个参数是截取的长度。
3)substring() 和 slice() 第一个参数是开始位置,第二个参数时结束位置(不包括) 【)
4)substring() 参数出现负数,默认为0;参数1>参数2时,自动换位 。

const str = "Hello world!";
console.log(str.substr(2, 4));   // "llo "
console.log(str.substring(2, 4));   // "ll"
console.log(str.slice(2, 4));       // "ll"
console.log(str.substring(-1,3));   // "Hel"   有负数变为0
console.log(str.substring(4,0));   // "Hell"   参数1>参数2,交换两个参数

有关三者详细使用区别请看 JavaScript中substr(),substring(),slice()的使用和区别

5. split / join

字符串 分割成 子串数组 或将一个 字符串数组 合并成一个 字符串

const str = "apple,pear,banana";
console.log(str.split(","));   // ["apple", "pear", "banana"]
const arr = ["apple", "pear", "banana"];
console.log(arr.join("|"));    // "apple|pear|banana"

6. toUpperCase / toLowerCase

将字符串转换成大写或小写。

const str = "Hello World!";
console.log(str.toUpperCase());   // "HELLO WORLD!"
console.log(str.toLowerCase());   // "hello world!"
// 字符串反转
const str ='abcdefg'
console.log(str.split('').reverse().join(''))   // gfedcba

7. replace

查找并替换字符串中的特定文本。
参数1是旧的,参数2是新的。

const str = "hello world!";
console.log(str.replace("world", "tichui"));   // "hello tichui!"
// 清除“数字”以外字符
const tel= "151 8989 8966";
console.log(tel.replace(/[^\d]/g, '')  // 15189898966

8. trim

用于删除字符串的头尾空白符。

const str = '    hello world!     '  
console.log(str.trim());   // "hello world!"

9. test

用于检测参数字符串是否符合检测表达式描述的规则,返回布尔值

// 校验手机号是否符合校验规则
let reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
const str = "15189898966";
console.log(reg.test(str));   // true

10. match

match() 方法可在字符串内检索指定的值,或找到一个或多个正则表达式的匹配。

var str2 = "89.5+7*5-9/3.0+8.5";
var num3 = str2.match(/\d+(\.\d+)?/g); 
console.log(num3); // ["89.5", "7", "5", "9", "3.0", "8.5"]
var num4 = str2.match(/[^\d\.]/g); 
console.log(num4); // ["+", "*", "-", "/", "+"]

注意: match() 方法将检索字符串 String Object,以找到一个或多个与 regexp 匹配的文本。这个方法的行为在很大程度上有赖于 regexp 是否具有标志 g。如果 regexp 没有标志 g,那么 match() 方法就只能在 stringObject 中执行一次匹配。如果没有找到任何匹配的文本, match() 将返回 null。否则,它将返回一个数组,其中存放了与它找到的匹配文本有关的信息。

猜你喜欢

转载自blog.csdn.net/weixin_45811256/article/details/130689847