JavaScript 常用字符串方法

213 阅读5分钟

1. charAt()

描述

charAt()返回指定索引位置的字符。字符串中的字符从左向右索引,第一个字符的索引值为 0,最后一个字符(假设该字符位于字符串 stringName 中)的索引值为 stringName.length - 1。 如果指定的 index 值超出了该范围,则返回一个空字符串。

语法

str.charAt(index)

示例

let str = 'hello world'
console.log(str.charAt(6)) // 返回 w
console.log(str.charAt(200)) // 返回 空字符串

2. indexOf()

描述

indexOf() 方法返回调用它的 String 对象中第一次出现的指定值的索引,从 fromIndex 处进行搜索。如果未找到该值,则返回 -1。

语法

str.indexOf(searchValue [, fromIndex])

示例

let str = 'hello world world'
console.log(str.indexOf('world'))     // 返回 6
console.log(str.indexOf('world', 0))  // 返回 6
console.log(str.indexOf('world', 6))  // 返回 6
console.log(str.indexOf('world', 7))  // 返回 12
console.log(str.indexOf('world', 13)) // 返回 -1
console.log(str.indexOf('hollo'))     // 返回 -1

3. lastIndexOf()

描述

lastIndexOf() 方法返回调用String 对象的指定值最后一次出现的索引,在一个字符串中的指定位置 fromIndex从后向前搜索。如果没找到这个特定值则返回-1 。

语法

str.lastIndexOf(searchValue[, fromIndex])

示例

'canal'.lastIndexOf('a');     // returns 3(没有指明fromIndex则从末尾l处开始反向检索到的第一个a出现在l的后面,即index为3的位置)
'canal'.lastIndexOf('a', 2);  // returns 1(指明fromIndex为2则从n处反向向回检索到其后面就是a,即index为1的位置)
'canal'.lastIndexOf('a', 0);  // returns -1(指明fromIndex为0则从c处向左回向检索a发现没有,故返回-1)
'canal'.lastIndexOf('x');     // returns -1
'canal'.lastIndexOf('c', -5); // returns 0(指明fromIndex为-5则视同0,从c处向左回向查找发现自己就是,故返回0)
'canal'.lastIndexOf('c', 0);  // returns 0(指明fromIndex为0则从c处向左回向查找c发现自己就是,故返回自己的索引0)
'canal'.lastIndexOf('');      // returns 5
'canal'.lastIndexOf('', 2);   // returns 2

4. toLowerCase()toUpperCase()

描述

toLowerCase() 会将调用该方法的字符串值转为小写形式,并返回。
toLowerCase() 会将调用该方法的字符串值转为小写形式,并返回。

语法

str.toLowerCase()
str.toUpperCase()

示例

console.log('中文简体 zh-CN || zh-Hans'.toLowerCase()); // 中文简体 zh-cn || zh-hans
console.log( "ALPHABET".toLowerCase() );  // "alphabet"

console.log('alphabet'.toUpperCase()); // 'ALPHABET'

5. slice()

描述

slice() 方法提取某个字符串的一部分,并返回一个新的字符串,且不会改动原字符串。

语法

str.slice(beginIndex[, endIndex])

6. substring()

描述

substring() 方法返回一个字符串在开始索引到结束索引之间的一个子集, 或从开始索引直到字符串的末尾的一个子集。

语法

str.substring(indexStart[, indexEnd])

7. substr()

描述

substr() 方法返回一个字符串中从指定位置开始到指定字符数的字符。

语法

str.substr(start[, length])

8. split()

描述

split() 方法使用指定的分隔符字符串将一个String对象分割成子字符串数组,以一个指定的分割字串来决定每个拆分的位置。

语法

str.split([separator[, limit]])

示例

"hello world haha hehe xixi".split(' ', 2) // (2) ["hello", "world"]

9. replace()

描述

replace() 方法返回一个由替换值(replacement)替换部分或所有的模式(pattern)匹配项后的新字符串。模式可以是一个字符串或者一个正则表达式,替换值可以是一个字符串或者一个每次匹配都要调用的回调函数。如果pattern是字符串,则仅替换第一个匹配项。

语法

str.replace(regexp|substr, newSubStr|function)

示例

const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';

console.log(p.replace('dog', 'monkey'));
// expected output: "The quick brown fox jumps over the lazy monkey. If the dog reacted, was it really lazy?"

const regex = /Dog/ig;
console.log(p.replace(regex, 'ferret'));
// expected output: "The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?"

10. match()

描述

match() 方法检索返回一个字符串匹配正则表达式的结果。

语法

str.match(regexp)

示例

"Hello World JavaScript HAha".match(/[A-Z]/g) // ["H", "W", "J", "S", "H", "A"]

ES6 字符串新增方法

1. includes()

描述

includes() 方法用于判断一个字符串是否包含在另一个字符串中,根据情况返回 true 或 false。

语法

str.includes(searchString[, position])

2. startsWith()

描述

startsWith() 方法用来判断当前字符串是否以另外一个给定的子字符串开头,并根据判断结果返回 true 或 false。

语法

str.startsWith(searchString[, position])

3. endsWith()

描述

endsWith()方法用来判断当前字符串是否是以另外一个给定的子字符串“结尾”的,根据判断结果返回 true 或 false。

语法

str.endsWith(searchString[, length])

4. padStart()

描述

padStart() 方法用另一个字符串填充当前字符串(如果需要的话,会重复多次),以便产生的字符串达到给定的长度。从当前字符串的左侧开始填充。

语法

str.padStart(targetLength [, padString])

5. padEnd()

描述

padEnd() 方法会用一个字符串填充当前字符串(如果需要的话则重复填充),返回填充后达到指定长度的字符串。从当前字符串的末尾(右侧)开始填充。

语法

str.padEnd(targetLength [, padString])

6. replaceAll()

描述

replaceAll() 方法返回一个新字符串,新字符串所有满足 pattern 的部分都已被replacement 替换。pattern可以是一个字符串或一个 RegExp, replacement可以是一个字符串或一个在每次匹配被调用的函数。
原始字符串保持不变。

语法

const newStr = str.replaceAll(regexp|substr, newSubstr|function)

示例

// 历史上,字符串的实例方法replace()只能替换第一个匹配。
'aabbcc'.replace('b', '_')  // 'aa_bcc'
// 如果要替换所有的匹配,不得不使用正则表达式的g修饰符。
'aabbcc'.replace(/b/g, '_') // 'aa__cc'
// ES2021 引入了replaceAll()方法,可以一次性替换所有匹配。
'aabbcc'.replaceAll('b', '_') // 'aa__cc'