当前位置: 首页 > news >正文

妈妈再也不用担心字符串方法啦!——js String实例方法汇总

js String实例方法笔记

at

at() 方法接受一个整数值,并返回一个新的 String

const sentence = 'The quick brown fox jumps over the lazy dog.';let index = 5;console.log(`An index of ${index} returns the character ${sentence.at(index)}`);
// Expected output: "An index of 5 returns the character u"index = -4;console.log(`An index of ${index} returns the character ${sentence.at(index)}`);
// Expected output: "An index of -4 returns the character d"
charAt

返回一个由给定索引处的单个 UTF-16 码元构成的新字符串。

const sentence = 'The quick brown fox jumps over the lazy dog.';const index = 4;console.log(`The character at index ${index} is ${sentence.charAt(index)}`);
// Expected output: "The character at index 4 is q"

charAt() 和使用方括号表示法访问指定索引处的字符非常相似。它们的主要区别在于:

  • charAt() 尝试将 index 转换为整数,而方括号表示法不会,直接使用 index 作为属性名。
  • 如果 index 超出范围,charAt() 返回一个空字符串,而方括号表示法返回 undefined
charAt和at的区别
  • at() 方法则是相对较新的,在ECMAScript 2021(也称为ES12)中引入。
  • charAt不接受负值,at在相对范围内接受负值(-1 表示最后一个字符)
  • 对于无效索引,at返回undefined,而charAt返回空字符串""
charCodeAt

返回给定索引处的 UTF-16 码元

const sentence = 'The quick brown fox jumps over the lazy dog.';const index = 4;console.log(`Character code ${sentence.charCodeAt(index)} is equal to ${sentence.charAt(index,)}`,
);
// Expected output: "Character code 113 is equal to q"
codePointAt

codePointAt() 方法返回一个非负整数,该整数是从给定索引开始的字符的 Unicode 码位值。请注意,索引仍然基于 UTF-16 码元,而不是 Unicode 码位。

const icons = '☃★♲';console.log(icons.codePointAt(1));
// Expected output: "9733"
concat()

将字符串参数连接到调用的字符串,并返回一个新的字符串

concat(str1, str2, /* …, */ strN)const str1 = 'Hello';
const str2 = 'World';console.log(str1.concat(' ', str2));
// Expected output: "Hello World" console.log(str2.concat(', ', str1));
// Expected output: "World, Hello"
endsWith

endsWith() 方法用于判断一个字符串是否以指定字符串结尾,如果是则返回 true,否则返回 false

const str1 = 'Cats are the best!';console.log(str1.endsWith('best!'));
// Expected output: trueconsole.log(str1.endsWith('best', 17));
// Expected output: trueconst str2 = 'Is this a question?';console.log(str2.endsWith('question'));
// Expected output: false
  • 如果参数被省略或传入 undefinedendsWith() 方法会在字符串中搜索 "undefined"
includes

执行区分大小写的搜索,以确定是否可以在一个字符串中找到另一个字符串,并根据情况返回 truefalse

includes(searchString, position)
//searchString待查找字符串
//position开始位置const sentence = 'The quick brown fox jumps over the lazy dog.';const word = 'fox';console.log(`The word "${word}" ${sentence.includes(word) ? 'is' : 'is not'} in the sentence`,
);
// Expected output: "The word "fox" is in the sentence"
indexOf

在字符串中搜索指定子字符串,并返回其第一次出现的位置索引,没有则返回-1

indexOf(searchString, position)
//searchString待查找字符串
//position开始位置const paragraph = "I think Ruth's dog is cuter than your dog!";const searchTerm = 'dog';
const indexOfFirst = paragraph.indexOf(searchTerm);console.log(`The index of the first "${searchTerm}" is ${indexOfFirst}`);
// Expected output: "The index of the first "dog" is 15"console.log(`The index of the second "${searchTerm}" is ${paragraph.indexOf(searchTerm,indexOfFirst + 1,)}`,
);
// Expected output: "The index of the second "dog" is 38"
  • 要搜索的子字符串。所有传入值都会被强制转换为字符串,因此如果该参数被省略或传入 undefinedindexOf() 方法会在字符串中搜索 "undefined"
lastIndexOf

在字符串中搜索指定子字符串,并返回其最后一次出现的位置索引,没有则返回-1

const paragraph = "I think Ruth's dog is cuter than your dog!";const searchTerm = 'dog';console.log(`Index of the last ${searchTerm} is ${paragraph.lastIndexOf(searchTerm)}`,
);
// Expected output: "Index of the last "dog" is 38"
  • 对于position的说明
    • 'hello world hello'.lastIndexOf('world', 4) 返回 -1——因为虽然子字符串 world 在索引 6 处出现,但该位置不小于或等于 4
    • 'hello world hello'.lastIndexOf('hello', 99) 返回 12——因为小于或等于 99 的位置中,最后一次出现 hello 的位置是索引 12
    • 'hello world hello'.lastIndexOf('hello', 0)'hello world hello'.lastIndexOf('hello', -5) 都返回 0——因为两者都导致该方法只在索引 0 处查找 hello
  • 其实和indexOf一样,indexOf截掉[0,position)再查找,lastIndexOf保留(positon,length-1]再查找
match

检索字符串与正则表达式进行匹配的结果,返回一个Array

match(regexp)const paragraph = 'The quick brown fox jumps over the lazy dog. It barked.';
const regex = /[A-Z]/g;
const found = paragraph.match(regex);console.log(found);
// Expected output: Array ["T", "I"]
  • 如果你没有给出任何参数并直接使用 match() 方法,你将会得到一个包含空字符串的数组:[""],因为这等价于 match(/(?:)/)
matchAll

返回一个迭代器,该迭代器包含了检索字符串与正则表达式进行匹配的所有结果(包括捕获组)。

const regexp = /t(e)(st(\d?))/g;
const str = 'test1test2';const array = [...str.matchAll(regexp)];console.log(array[0]);
// Expected output: Array ["test1", "e", "st1", "1"]console.log(array[1]);
// Expected output: Array ["test2", "e", "st2", "2"]
  • 一个匹配结果的可迭代迭代器对象(它不可重新开始)。每个匹配结果都是一个数组
  • regx必须携带全局标志(g)
padEnd

padEnd() 方法会将当前字符串从末尾开始填充给定的字符串(如果需要会重复填充),直到达到给定的长度。填充是从当前字符串的末尾开始的。不改变原字符串

padEnd(targetLength, padString)
//当前 str 填充后的长度。如果该值小于或等于 str.length,则会直接返回当前 str。
//用于填充当前 str 的字符串。如果 padString 太长,无法适应 targetLength,则会被截断:对于从左到右的语言,左侧的部分将会被保留;对于从右到左的语言,右侧的部分将会被保留。默认值为“ ”const str1 = 'Breaded Mushrooms';console.log(str1.padEnd(25, '.'));
// Expected output: "Breaded Mushrooms........"const str2 = '200';console.log(str2.padEnd(5));
// Expected output: "200  "
padStart

同上,但是从开头开始

const str1 = '5';console.log(str1.padStart(2, '0'));
// Expected output: "05"const fullNumber = '2034399002125581';
const last4Digits = fullNumber.slice(-4);
const maskedNumber = last4Digits.padStart(fullNumber.length, '*');console.log(maskedNumber);
// Expected output: "************5581"
repeat

返回指定数量的原字符串,这些字符串无缝连接

repeat(count)
//介于 0 和 +Infinity 之间的整数。表示在新构造的字符串中重复了多少遍原字符串。const mood = 'Happy! ';console.log(`I feel ${mood.repeat(3)}`);
// Expected output: "I feel Happy! Happy! Happy! "
replace

替换指定内容,不改变原字符串

replace(pattern, replacement)const paragraph = "I think Ruth's dog is cuter than your dog!";console.log(paragraph.replace("Ruth's", 'my'));
// Expected output: "I think my dog is cuter than your dog!"const regex = /Dog/i;
console.log(paragraph.replace(regex, 'ferret'));
// Expected output: "I think Ruth's ferret is cuter than your dog!"
  • pattern 可以是字符串或 RegExpreplacement 可以是字符串或一个在每次匹配时调用的函数。如果 pattern 是字符串,则只会替换第一个匹配项。
  • 如果是pattern是RegExp,则得以i结尾,因为相当于字符串只匹配一个
replaceAll

替换全部指定内容,不改变原字符串

const paragraph = "I think Ruth's dog is cuter than your dog!";console.log(paragraph.replaceAll('dog', 'monkey'));
// Expected output: "I think Ruth's monkey is cuter than your monkey!"// Global flag required+ when calling replaceAll with regex
const regex = /Dog/gi;
console.log(paragraph.replaceAll(regex, 'ferret'));
// Expected output: "I think Ruth's ferret is cuter than your ferret!"
  • 如果是pattern是RegExp,则得以gi结尾,因为相当于字符串替换全部
  • 简而言之,就是无论replace还是replaceAll在pattern是RegExp时,RegExp也需要满足函数意义
search

用于在 String 对象中执行正则表达式的搜索,寻找匹配项.匹配成功则返回索引,否则返回-1

const paragraph = "I think Ruth's dog is cuter than your dog!";// Anything not a word character, whitespace or apostrophe
const regex = /[^\w\s']/g;console.log(paragraph.search(regex));
// Expected output: 41console.log(paragraph[paragraph.search(regex)]);
// Expected output: "!"
slice

提取字符串的一部分,并将其作为新字符串返回,而不修改原始字符串。

slice(indexStart)
slice(indexStart, indexEnd)const str = 'The quick brown fox jumps over the lazy dog.';console.log(str.slice(31));
// Expected output: "the lazy dog."console.log(str.slice(4, 19));
// Expected output: "quick brown fox"console.log(str.slice(-4));
// Expected output: "dog."console.log(str.slice(-9, -5));
// Expected output: "lazy"
  • indexStart为0或者不传参即为浅拷贝整个字符串
split

接受一个模式,通过搜索模式将字符串分割成一个有序的子串列表,将这些子串放入一个数组,并返回该数组。

即:在父串中一遇到separator,就分割一个子串,最后返回这些子串组成的数组

split(separator)
split(separator, limit)
//limit:数组最大长度,一旦数组长度达到limit,再切割出的子串就不加入返回数组const str = 'The quick brown fox jumps over the lazy dog.';const words = str.split(' ');
console.log(words[3]);
// Expected output: "fox"const chars = str.split('');
console.log(chars[8]);
// Expected output: "k"const strCopy = str.split();
console.log(strCopy);
// Expected output: Array ["The quick brown fox jumps over the lazy dog."]
startsWith

判断当前字符串是否以另外一个给定的子字符串开头,返回布尔值

startsWith(searchString)
startsWith(searchString, position)
//position:开始位置const str1 = 'Saturday night plans';console.log(str1.startsWith('Sat'));
// Expected output: trueconsole.log(str1.startsWith('Sat', 3));
// Expected output: false
String.prototype[Symbol.iterator]

实现可迭代

  • 就放这儿看看,具体的要看迭代对象
substring

返回该字符串从起始索引到结束索引(不包括)的部分,如果未提供结束索引,则返回到字符串末尾的部分。

substring(indexStart)
substring(indexStart, indexEnd)const str = 'Mozilla';console.log(str.substring(1, 3));
// Expected output: "oz"console.log(str.substring(2));
// Expected output: "zilla"
  • 左闭右开,没有右就到末尾
toLocaleLowerCase

根据所处地方规则,将字符串转换为小写形式并返回

toLocaleLowerCase()
toLocaleLowerCase(locales)
//locales:区域设置const dotted = 'İstanbul';console.log(`EN-US: ${dotted.toLocaleLowerCase('en-US')}`);
// Expected output: "i̇stanbul"console.log(`TR: ${dotted.toLocaleLowerCase('tr')}`);
// Expected output: "istanbul"
toLocaleUpperCase

根据所处地方规则,将字符串转换为大写形式并返回

toLocaleUpperCase()
toLocaleUpperCase(locales)
//locales:区域设置const city = 'istanbul';console.log(city.toLocaleUpperCase('en-US'));
// Expected output: "ISTANBUL"console.log(city.toLocaleUpperCase('TR'));
// Expected output: "İSTANBUL"
toLowerCase

将字符串转换为小写形式

toLowerCase()const sentence = 'The quick brown fox jumps over the lazy dog.';console.log(sentence.toLowerCase());
// Expected output: "the quick brown fox jumps over the lazy dog."
toUpperCase

将字符串转换为大写形式

const sentence = 'The quick brown fox jumps over the lazy dog.';console.log(sentence.toUpperCase());
// Expected output: "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG."
toString

StringtoString() 方法返回该字符串的值。

const stringObj = new String('foo');console.log(stringObj);
// Expected output: String { "foo" }console.log(stringObj.toString());
// Expected output: "foo"
  • String 对象重写了 ObjecttoString 方法;它不会继承 Object.prototype.toString()。对于 String 值,toString 方法返回字符串本身(如果它是原始值)或 String 对象封装的字符串。它的实现与 String.prototype.valueOf() 完全相同。
  • 由于 String 没有 [Symbol.toPrimitive]() 方法,当一个 String 对象在期望字符串的上下文中使用时(比如在模板字面量中),JavaScript 会自动调用 toString() 方法。然而,String 原始值不会使用 toString() 方法来进行字符串强制转换——因为它们已经是字符串,所以不会进行转换。
trim

trim() 方法会从字符串的两端移除空白字符,并返回一个新的字符串,而不会修改原始字符串。

const greeting = '   Hello world!   ';console.log(greeting);
// Expected output: "   Hello world!   ";console.log(greeting.trim());
// Expected output: "Hello world!";
trimEnd

trimEnd() 方法会从字符串的结尾移除空白字符,并返回一个新的字符串,而不会修改原始字符串。trimRight() 是该方法的别名。

const greeting = '   Hello world!   ';console.log(greeting);
// Expected output: "   Hello world!   ";console.log(greeting.trimEnd());
// Expected output: "   Hello world!";
trimStart

trimStart() 方法会从字符串的开头移除空白字符,并返回一个新的字符串,而不会修改原始字符串。trimLeft() 是该方法的别名。

const greeting = '   Hello world!   ';console.log(greeting);
// Expected output: "   Hello world!   ";console.log(greeting.trimStart());
// Expected output: "Hello world!   ";
valueOf

valueOf() 方法返回 String 对象的字符串值。

返回:一个字符串,表示给定 String 对象的原始值。

const stringObj = new String('foo');console.log(stringObj);
// Expected output: String { "foo" }console.log(stringObj.valueOf());
// Expected output: "foo"
  • 值和String.prototype.toString()等价
  • 此方法通常由 JavaScript 在内部调用,而不是在代码中显式调用。

http://www.mrgr.cn/news/33807.html

相关文章:

  • 分布式安装LNMP
  • 基于 Web 的工业设备监测系统:非功能性需求与标准化数据访问机制的架构设计
  • 传输层 III(TCP协议——可靠传输)【★★★★】
  • 【Spring 底层原理】手搓一个Spring框架
  • 【busybox记录】【shell指令】numfmt
  • 嵌入式系统基础讲解
  • 用apache httpd来实现反向代理
  • golang学习笔记3-变量的声明
  • CORS跨域+Nginx配置、Apache配置
  • 2024.9.22
  • screen使用——关机时在服务器上跑代码
  • 蓝桥杯嵌入式的学习总结
  • UE学习篇ContentExample解读-----------Blueprint_Overview
  • 《深度学习》—— 卷积神经网络(CNN)的简单介绍和工作原理
  • 深度学习与应用:人体关键点检测
  • SpringBoot项目License证书生成与验证(TrueLicense) 【记录】
  • 一种求解无人机三维路径规划的高维多目标优化算法,MATLAB代码
  • Java-Part 0
  • 2009考研数学真题解析-数二:
  • 【JavaWeb】一、Web 开发概述