[Javascript 进阶]-字符串

摘要

本文主要收录了常用的javascript的字符串操作函数,并附有较为详细的说明和代码样例,掌握之后能够处理大部分字符串问题。

查找

String.prototype.at(index: Number)

返回对应序号的字符串,可以为负数,负数则是从最后一个字符串开始查找。

js 复制代码
const hello = 'hello';
console.log(hello.at(1)); // 'e'
console.log(hello.at(-1)); // 'o'

相比较于取最后几位字符串来说at比较优雅直观;

js 复制代码
const lengthWay = hello[hello.length - 2];
const atWay = hello.at(-2);

String.prototype.includes(searchString: String)

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

js 复制代码
const sentence = 'The quick brown fox jumps over the lazy dog.';
const word = 'fox';
sentence.includes(word); // true

String.prototype.match(regex: RegExp)

检索字符串与正则表达式进行匹配的结果,返回匹配的数组,如果没有匹配的返回null。

js 复制代码
const hello = 'hello';
const regex = new RegExp('l', 'g');
hello.match(regex) // ["l","l"]

String.prototype.search(regex: RegExp)

在 String 对象中执行正则表达式的搜索,寻找匹配项,返回匹配的起始index。

js 复制代码
const hello = 'hello';
const regex = new RegExp('l', 'g');
console.log(hello.search(regex)) // 2

String.prototype.replace(pattern: RegExp | String, replacement: String)

replace() 方法返回一个新字符串,其中一个、多个或所有匹配的 pattern 被替换为 replacement。pattern 可以是字符串或 RegExp,replacement 可以是字符串或一个在每次匹配时调用的函数。如果 pattern 是字符串,则只会替换第一个匹配项。原始的字符串不会改变。

js 复制代码
const hello = 'hello';
const regex = new RegExp('l', 'g');
console.log(hello.replace(regex, 'L')) // "heLLo"
console.log(hello.replace('l', 'L')) // "heLlo"

String.prototype.replaceAll(pattern, replacement)

replace() 一样,只是会替换所有匹配的项目,就算是没用正则表达式。

String.prototype.startsWith(searchString: String, endIndex: Number)

判断当前字符串是否以另外一个给定的子字符串开头,并根据判断结果返回 true 或 false,startIndex 是指定开始计算的位置。

js 复制代码
const str1 = 'Saturday';

console.log(str1.startsWith('Sat'));
// Expected output: true

console.log(str1.startsWith('Sat', 3));
// Expected output: false

String.prototype.endsWith(searchString: String, endIndex: Number)

用于判断一个字符串是否以指定字符串结尾,如果是则返回 true,否则返回 false,endIndex 是指定结束计算的位置。

js 复制代码
const str1 = 'Cats are the best!';

console.log(str1.endsWith('best!'));
// Expected output: true

console.log(str1.endsWith('best', 17));
// Expected output: true

console.log(str1.endsWith('best', 5));
// Expected output: false

截取

String.prototype.slice(startIndex: Number, endIndex: Number)

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

js 复制代码
const hello = 'hello';
console.log(hello.slice(1, 2))
console.log(hello.slice(2)) // 没有结束位置会截取到最后
console.log(hello.slice(-3)) // 可以为负数,从最后往前计算位置
console.log(hello.slice(-3, -1)) // startIndex 需要小于 endIndex 不然取不到任何值

String.prototype.trim()

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

js 复制代码
const greeting = '   Hello world!   ';

console.log(greeting);
// Expected output: "   Hello world!   ";

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

String.prototype.trimStart()

从字符串的开头移除空白字符,并返回一个新的字符串,而不会修改原始字符串。

js 复制代码
console.log(greeting.trimStart());
// Expected output: "Hello world!   ";

String.prototype.trimEnd()

从字符串的开头移除空白字符,并返回一个新的字符串,而不会修改原始字符串。

js 复制代码
console.log(greeting.trimEnd());
// Expected output: "   Hello world!";

格式化

String.prototype.padStart(maxLength: Number, placeholder: String)

用另一个字符串填充当前字符串(如果需要会重复填充),直到达到给定的长度。填充是从当前字符串的开头开始的,maxLength 需要大于0,否则不会进行追加。

js 复制代码
const str1 = '5';

console.log(str1.padStart(2, '0'));
// Expected output: "05"

console.log(str1.padStart(-1, '0'));
// Expected output: "5"

const fullNumber = '2034399002125581';
const last4Digits = fullNumber.slice(-4);
const maskedNumber = last4Digits.padStart(fullNumber.length, '*');

console.log(maskedNumber);
// Expected output: "************5581"

String.prototype.padEnd(maxLength: Number, placeholder: String)

用另一个字符串填充当前字符串(如果需要会重复填充),直到达到给定的长度。填充是从当前字符串的开头开始的,maxLength 如果小于当前字符串长度则不会进行追加。

js 复制代码
const str1 = 'Breaded Mushrooms';

console.log(str1.padEnd(25, '.'));
// Expected output: "Breaded Mushrooms........"

console.log(str1.padEnd(5, '.'));
// Expected output: "Breaded Mushrooms"

const str2 = '200';

console.log(str2.padEnd(5));
// Expected output: "200  "

String.prototype.repeat(count: Number)

返回一个新字符串,其中包含指定数量的所调用的字符串副本,这些副本连接在一起。

js 复制代码
const helloWorld3Times = `hello${' world'.repeat(3)}`;
console.log(helloWorld3Times); // "hello world world world"

String.prototype.toUpperCase()

将该字符串转换为大写形式,返回新字符串。

js 复制代码
const hello = 'hello';
console.log(hello.toUpperCase()) // 'HELLO'

String.prototype.toLowerCase()

将该字符串转换为小写形式,返回新字符串。

js 复制代码
const hello = 'HELLO';
console.log(hello.toLowerCase()) // 'hello'

参考文献

developer.mozilla.org/zh-CN/docs/...

相关推荐
随风一样自由6 小时前
【前端独角兽】刚进入前端领域的前端开发用jQuery还是Vue3?
前端·javascript·vue3·jquery
IMPYLH7 小时前
HTML 的 <data> 元素
前端·html
YHHLAI7 小时前
[特殊字符] 面试中的 Promise —— 从入门到精通
前端·javascript·面试
weixin_BYSJ19878 小时前
SpringBoot + MySQL 乒乓球运动员信息管理系统项目实战--附源码04954
java·javascript·spring boot·python·django·flask·php
沪飘大军8 小时前
ll-llm:一个零依赖、可插拔的 OpenAI 兼容 LLM 代理
javascript
kyriewen9 小时前
我扒了 GPT-5.6 的全部编程跑分——有一项 OpenAI 没敢放出来
前端·gpt·ai编程
前端H10 小时前
微前端 v3 架构升级:从加载隔离到状态协同
前端·架构·状态模式
山河木马10 小时前
GPU自动处理专题3-NDC怎么映射成屏幕像素坐标(视口变换)
javascript·webgl·图形学
陆枫Larry11 小时前
小程序包体积优化:用 SVG 图片替换 iconfont,并保留 CSS 控色能力
前端
Appthing11 小时前
在 TanStack Start 中使用 VitePWA 的正确配置
javascript