成为算法专家必须了解的 JavaScript 字符串方法

2025-06-07

成为算法专家必须了解的 JavaScript 字符串方法

在本文中,我想讨论一些 JavaScript 中最常用的基本字符串方法,它们在解决问题和算法时非常有用。

过去四周,我一直在 FreeCodeCamp 和 CodeWars 上练习算法求解,发现这些方法用得非常多。

如果你对数组方法感兴趣,可以查看我的帖子:
成为算法向导必须知道的 Javascript 数组方法

1)使用.length获取字符串的长度

let str = "i am a string";
console.log(str.length); //13

2) 使用.split()从字符串获取数组。记住,可以使用指定的分隔符字符串来确定每次拆分的位置。

const str = "Luke, I am your Father";
console.log(str.split());//[ 'Luke, I am your Father' ]
console.log(str.split(''));//["L", "u", "k", "e", ",", " ", "I", " ", "a", "m", " ", "y", "o", "u", "r", " ", "F", "a", "t", "h", "e", "r"]
console.log(str.split(' '));//[ 'Luke,', 'I', 'am', 'your', 'Father' ]
console.log(str.split(','));//[ 'Luke', ' I am your Father' ]

让我们看一个我在 CodeWars 上解决的简单算法,其中给定一串单词,函数必须返回一个等于单词长度的整数数组。

function wordsLength(str) {
  return str.split(' ') //first split the string at spaces to have an array of words;
            .map(word => word.length); //second use array map() to trasform any array element to its length with .length;
}

wordsLength('Luke, I am your father'); //[ 5, 1, 2, 4, 6 ]

3)使用toUpperCase()将字符串转换为大写

const str = 'I find your lack of faith disturbing.';
console.log(str.toUpperCase()); //I FIND YOUR LACK OF FAITH DISTURBING.

4)使用toLowerCase()将字符串转换为小写

const str = 'Help me, Obi-Wan Kenobi. You’re my only hope.';
console.log(str.toLowerCase()); //help me, obi-wan kenobi. you’re my only hope.

5) 检查字符串是否包含指定字符includes()。它将返回布尔值(true 或 false)。可以添加字符串中开始搜索的位置。

const str = 'The Force will be with you. Always.';
console.log(str.includes('Force')); //true
//Attention: it is case sensitive!
console.log(str.includes('force')); //false
//Often it will be better to transform the given string to lowercased 
//and then check if it includes or not what you are looking for.
const newStr = str.toLowerCase();
console.log(newStr.includes('force')); //true
//Add the position where to start searching
console.log(str.includes('w', 0)); //true
console.log(str.includes('T', 1)); //false

6)使用startWith()检查字符串是否以指定字符开头。它将返回一个布尔值,并可以添加开始搜索的位置。它区分大小写。

const str = 'Never tell me the odds!';
console.log(str.startsWith('Never')); //true
console.log(str.startsWith('Never', 1)); //false
console.log(str.startsWith('never', 0)); //false

7) 使用endsWith()检查字符串是否以指定字符结尾。它将返回一个布尔值,并且可以添加长度参数(可选)。它区分大小写。

const str = 'Do. Or do not. There is no try.';
console.log(str.endsWith('try.')); //true
console.log(str.endsWith('Try.')); //false
console.log(str.endsWith('try', 30)); //true
console.log(str.endsWith('try.', 30)); //false

7) 使用.indexOf()函数检查字符串中指定值是否首次出现。如果该值不在字符串中,则返回 -1。可以添加第二个参数,从指定索引处开始搜索。

const str = 'When gone am I, the last of the Jedi will you be. The Force runs strong in your family. Pass on what you have learned.';
console.log(str.indexOf('h')); //1
console.log(str.indexOf('H')); //-1
console.log(str.indexOf('h', 2)); //17
console.log(str.indexOf('J', str.length)); //-1

8) 使用.lastIndexOf()检查字符串中指定值的最后一次出现。如果该值不在字符串中,则返回 -1。可以添加字符串中最后一个字符的索引,作为匹配的开始。

const str = 'When gone am I, the last of the Jedi will you be. The Force runs strong in your family. Pass on what you have learned.';
console.log(str.lastIndexOf('h')); //105
console.log(str.lastIndexOf('h', 100)); //97
console.log(str.lastIndexOf('.')); //117
console.log(str.lastIndexOf('.', 0)); //-1

9)使用.repeat()重复给定的字符串

const str = 'There’s always a bigger fish.';
console.log(str.repeat(2));//There’s always a bigger fish.There’s always a bigger fish.
//Attention: count will be converted to integer!
console.log(str.repeat(5.5));//There’s always a bigger fish.There’s always a bigger fish.There’s always a bigger fish.There’s always a bigger fish.There’s always a bigger fish.

10) 使用replace()替换给定字符串中的模式。模式可以是字符串或正则表达式,替换项可以是字符串或每次匹配时调用的函数。注意:如果替换器或模式是字符串,则仅替换第一次出现的匹配项。

const string = 'Fear is the path to the dark side.';
console.log(string.replace('Fear', 'Tears')); //Tears is the path to the dark side.
console.log(string.replace(/a/gi, 'A'));//FeAr is the pAth to the dArk side.

11) 使用charAt()从字符串中获取特定字符。返回表示指定索引处字符(恰好一个 UTF-16 代码单元)的字符串。如果索引超出范围,则返回空字符串!

const string = 'Fear leads to anger';
console.log(string.charAt(1));//e
console.log(string.charAt(string.length - 1));//r
console.log(string.charAt(string.length));//'' Index out of range!
//Attention: if no index is provided the default one is 0;
console.log(string.charAt());//F

12) 使用charCodeAt()获取字符串中给定索引处字母的 UTF-16 编码。此方法对于 ROT13 或凯撒密码等算法非常有用。如果没有提供索引,则默认索引为 0。

const string = 'We must keep our faith in the Republic.';
console.log(string.charCodeAt(0));//87
console.log(string.charCodeAt(5));//115
//If you want all the UTF-16 values of any letter in a string
//split the string to have an array of letters
//map the array and change any letter to its utf-16 value with charCodeAt();
const utfValuesArr = string.split('').map(letter => letter.charCodeAt());
console.log(utfValuesArr);
//[87, 101, 32, 109, 117, 115, 116, 32, 107, 101, 101, 112, 32, 111, 117, 114, 32, 102, 97, 105, 116, 104, 32, 105, 110, 32, 116, 104, 101, 32, 82, 101, 112, 117, 98, 108, 105, 99, 46]

13) 使用静态String.fromCharCode()方法获取从指定的 UTF-16 代码单元序列创建的字符串

console.log(String.fromCharCode(65));//A
console.log(String.fromCharCode(105, 106, 107));//ijk
console.log(String.fromCharCode(32));//'' empty space!


const arr = [77, 97, 121, 32, 116, 104, 101, 32, 70, 111, 114, 99, 101, 32, 66, 101, 32, 87, 105, 116, 104, 32, 89, 111, 117];
const quote = arr.map(n => String.fromCharCode(n));
console.log(quote.join('')); //May the Force Be With You

14) 使用slice()获取字符串的一部分,并将其返回到新字符串中,而不会修改原始字符串。它需要两个参数:BeginIndex(切片起始位置)和可选的 EndIndex(切片终止位置)。如果没有提供 EndIndex,它将切片到字符串末尾。注意:负索引从字符串末尾向后计数。

const string = 'I’m just a simple man trying to make my way in the universe.';
console.log(string.slice(1));//’m just a simple man trying to make my way in the universe.
console.log(string.slice(0,10));//I’m just a
console.log(string.slice(-3));//se.

15) 使用substring()获取字符串中起始索引和结束索引之间或到字符串末尾的部分。注意:任何小于 0 或大于 stringName.length 的参数值都将分别被视为 0 和 stringName.length。任何 NaN 的参数值都将被视为 0。

const string = 'Darth Vader';
console.log(string.substring(0));//Darth Vader
console.log(string.substring(6));//Vader
console.log(string.substring(1,6));//arth

16) 使用trim()删除字符串两端的空格

const string = '      Yoda     ';
console.log(string.trim());//Yoda

这并不是一份详尽的 JavaScript 字符串方法清单,而是我认为在解决问题和算法方面最重要的方法清单。
为了提高 JavaScript 水平和解决问题的能力,我建议多尝试所有这些方法,并订阅FreeCodeCampCodewars,在那里你可以找到很多可用的算法,并巩固你的 JavaScript 知识。
Codewars上,你可以找到关于“字符串”的 7 级或 6 级算法,并用它们进行训练。这将会非常有趣!

根据大家的反应和评论,我将用新的信息和一些有关字符串的算法来更新这篇文章。

代码长存,繁荣昌盛

文章来源:https://dev.to/uptheirons78/javascript-string-methods-you-must-know-to-become-an-algorithms-wizard-c84
PREV
停止重复工作并开始编写您的快速 API 🚀
NEXT
用 Python 做 9 件奇妙的事