JS字符串常用方法汇总

字符串的常用方法

  1. at()
  • 作用:查找字符串中指定索引位置的内容并返回
  • 语法:at(index) index为返回的字符串字符的索引(位置)。如果使用负数,返回的字符将从字符串的末端开始倒数。
  • 返回值: 指定位置的单个 UTF-16 码元组成的 String。如果找不到指定的索引,则返回 undefined。
const str = 'hello world'
const r = str.at(4)
console.log(r) // "o"
const r1 = str.at(-4)
console.log(r1) // "o"
  • 方法对比: 比较不同的方法来实现选择 String 的倒数第二个字符。at() 方法更简洁,可读性高。
const myString = "Every green bus drives fast.";

// 使用 length 属性和 charAt() 方法
const lengthWay = myString.charAt(myString.length - 2);
console.log(lengthWay); // 't'

// 使用 slice() 方法
const sliceWay = myString.slice(-2, -1);
console.log(sliceWay); // 't'

// 使用 at() 方法
const atWay = myString.at(-2);
console.log(atWay); // 't'
  1. charAt()
  • 作用:查找字符串中指定索引位置的内容并返回
  • 语法:charAt(index) index为要返回的字符的索引,从零开始。undefined 会被转换为 0。
  • 返回值:索引位置对应的字符,如果 index 超出了 0 – str.length - 1 的范围,charAt() 将返回一个空字符串。
const str = 'hello world'
const r = str.charAt(2)
console.log(r) // l
  • 方法比较:charAt() 和使用方括号表示法访问指定索引处的字符区别在于
    • charAt() 将 index 转换为整数,而方括号直接使用 index 作为属性名。
    • 如果 index 超出范围,charAt() 返回一个空字符串,而方括号表示法返回 undefined。
  1. charCodeAt()
  • 作用:返回对应索引位置的unicode码
  • 语法: charCodeAt(index)
  • 返回值:该索引位置的对应字符的编码(十进制)。介于 0 和 65535 之间,表示指定 index 处字符的 UTF-16 码元值。如果 index 超出了 0 到 str.length - 1 的范围,则 charCodeAt() 返回 NaN。
const str = 'hello world'
const r = str.charCodeAt(2)
console.log(r) // 108
  1. codePointAt()
  • 作用:获取给定索引处的完整 Unicode 码
  • 语法:codePointAt(index)
  • 返回值:非负整数,表示给定 index 处字符的码位值。
  • 描述:Unicode 码位范围从 0 到 1114111(0x10FFFF)。在 UTF-16 中,每个字符串索引是一个取值范围为 0 – 65535 的码元。较高的码位由一个由一对 16 位代理伪字符表示。因此,codePointAt() 返回的码位可能跨越两个字符串索引。有关 Unicode 的信息,UTF-16 字符、Unicode 码位和字素簇
const icons = '☃★♲';
console.log(icons.codePointAt(1));
// Expected output: "9733"
  1. concat()
  • 作用:拼接字符串
  • 语法:concat(str1, str2, /* …, */ strN) 要连接到 str 的一个或多个字符串。
  • 返回值:包含所传参数的多个字符串文本组合的新字符串。
const str1 = 'Hello';
const str2 = 'World';
console.log(str1.concat(' ', str2));
// Expected output: "Hello World"
console.log(str2.concat(', ', str1));
// Expected output: "World, Hello"
  1. endsWith()
  • 作用:判断一个字符串是否以指定字符串结尾,如果是则返回 true,否则返回 false。
  • 语法:endsWith(searchString, endPosition) endPosition可选,searchString是要搜索的作为结尾的字符串。
  • 返回值:true/false
const str1 = 'Hello World!';
console.log(str1.endsWith('World!'));
// Expected output: true
console.log(str1.endsWith('World', 17));
// Expected output: true
  1. includes()
  • 作用:搜索字符串中是否包含指定字符串
  • 语法:includes(searchString, position) position可选,searchString是要搜索的字符串, 区分大小写。
  • 返回值:true/false
const str = 'hello world'
const r = str.includes('wor')
console.log(r) // true
  1. indexOf()
  • 作用:在字符串中搜索指定子字符串,返回其第一次出现的位置索引。
  • 语法:indexOf(searchString,position) position可选,指定搜索的起始位置。
  • 返回值:如果有该字符则返回字符索引位置,否则返回-1
const str = 'hello world'
const r = str.indexOf('l')
console.log(r) // 2 
const r1 = str.indexOf('w', 3)
console.log(r1) // 6 
const r2 = str.indexOf('w', 7)
console.log(r2) // -1 
  1. lastIndexOf()
  • 作用:从后向前检测该字符在字符串内的索引位置
  • 语法:lastIndexOf(searchString,position)
  • 返回值:如果有该字符则返回字符索引位置,否则返回-1
const str = 'hello world'
const r = str.lastIndexOf('l')
console.log(r) // 9 
const r1 = str.lastIndexOf('l', 8)
console.log(r1) // 3
  1. match()
  • 作用:用正则检索字符串
  • 语法:match(regexp)
  • 返回值:Array,如果存在全局标志g,返回正则匹配的所有结果,但不返回捕获组;如果没有g标志,则返回第一个匹配及相关捕获组。
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); // ['T', 'I']
  1. matchAll()
  • 作用:检索字符串与正则匹配的所有结果
  • 语法:matchAll(regexp)
  • 返回值:匹配结果的数组,每个结果都是一个数组,与RegExp.prototype.exec() 的返回值相同
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"]
  1. normalize()
  • 作用:获取字符串的 Unicode 标准化形式
  • 语法: normalize(form) form可选,是 “NFC”、“NFD”、“NFKC” 或 “NFKD”,默认为NFC
  • 返回值:字符串
const name1 = '\u0041\u006d';
console.log(name1.normalize()) //  "Am"
  1. padEnd()
  • 作用:向字符串末尾填充指定字符串
  • 语法:padEnd(targetLength, padString) targetLength填充后的长度,padString可选要填充的字符串
  • 返回值:填充后的字符串
const str = 'hello world'
const r = str.padEnd(15, '!')
console.log(r) // "hello world!!!!"
  1. padStart()
  • 作用:向字符串开始填充指定字符串
  • 语法:padStart(targetLength, padString) targetLength填充后的长度,padString可选要填充的字符串
  • 返回值:填充后的字符串
const str = 'hello world'
const r = str.padStart(15, '!')
console.log(r) // "!!!!hello world"
  1. raw()
  • 作用: 获取模板字符串的原始字符串形式
  • 语法:String.raw(strings, …substitutions) strings格式正确的模板字符串数组对象,…substitutions替换表达式对应的值
  • 返回值:模板字符串的原始字符串
const filePath = String.raw`C:\Development\profile\aboutme.html`;

console.log(`The file was uploaded from: ${filePath}`);
// Expected output: "The file was uploaded from: C:\Development\profile\aboutme.html"
  1. repeat()
  • 作用:获取包含指定数量的字符串副本的拼接字符串
  • 语法:repeat(count)
  • 返回值:新字符串
const mood = 'Happy! ';
console.log(`I feel ${mood.repeat(3)}`); // "I feel Happy! Happy! Happy! "
  1. replace()
  • 作用:替换字符串中指定内容
  • 语法:replace(pattern, replacement) 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!"
  1. replaceAll()
  • 作用:替换字符串中所有指定内容
  • 语法:replaceAll(pattern, replacement) pattern可以是字符串或者正则表达式,replacement可以是字符串或函数
  • 返回值:被替换后的字符串
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!"
  1. search()
  • 作用:利用正则搜索字符串中的匹配项
  • 语法:search(regexp)
  • 返回值:如果匹配成功,则返回正则表达式在字符串中首次匹配的索引;否则,返回 -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: 41

console.log(paragraph[paragraph.search(regex)]);
// Expected output: "!"
  1. slice()
  • 作用:截取字符串的一部分
  • 语法:slice(indexStart, indexEnd) indexEnd可选,包含indexStart,不包含indexEnd
  • 返回值:截取的新字符串
const str = 'hello world'
const r = str.slice(3)
console.log(r) // "lo world"
console.log(str.slice(3,5)) // "lo"
console.log(str.slice(-3)) // "rld"
  1. split()
  • 作用:使用特定分割标记分割字符串为数组
  • 语法:split(separator, limit) separator为分隔符,limit为数量限制,可选。
  • 返回值:数组
const str = 'The quick brown fox jumps over the lazy dog.';
const words = str.split(' ');
console.log(words) // ["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog."]
  1. startsWith()
  • 作用:判断字符串是否以指定子字符串开头
  • 语法:startsWith(searchString, position) searchString开头的子字符串,position可选,为开始判断的索引位置。
  • 返回值:true/false
const str = 'hello world'
console.log(str.startsWith('he')) // true
console.log(str.startsWith('he', 3)) // false
  1. substring
  • 作用:截取字符串,substr已弃用,区别在于substr的两个参数的start和length,substring是start和end。substring() 方法在 indexStart 大于 indexEnd 的情况下会交换它的两个参数,这意味着仍会返回一个字符串。而 slice() 方法在这种情况下返回一个空字符串。
  • 语法:substring(indexStart, indexEnd)
  • 返回值:返回该字符串从起始索引到结束索引(不包括)的部分,如果未提供结束索引,则返回到字符串末尾的部分。
const str = 'hello world'
const r = str.substring(2, 8)
console.log(r) // "llo wo"
  1. 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"
  1. toLocaleUpperCase()
  • 作用:按照特定区域将字符串转为大写形式
  • 语法:toLocaleUpperCase(locales) locales可选,
  • 返回值:字符串的大写形式
const city = 'istanbul';
console.log(city.toLocaleUpperCase('en-US'));
// Expected output: "ISTANBUL"
console.log(city.toLocaleUpperCase('TR'));
// Expected output: "İSTANBUL"
  1. toLowerCase()
  • 作用:将字符串转为小写形式
  • 语法:toLowerCase()
  • 返回值:字符串的小写形式
const str = 'Hello World'
console.log(str.toLocaleLowerCase()) // hello world
  1. toUpperCase()
  • 作用:将字符串转为大写形式
  • 语法:toUpperCase()
  • 返回值:字符串的大写形式
const str = 'hello world'
console.log(str.toUpperCase()) // HELLO WORLD
  1. toString()
  • 作用:返回该字符串的值
  • 语法:toString()
  • 返回值:字符串
const stringObj = new String('foo');

console.log(stringObj);
// Expected output: String { "foo" }

console.log(stringObj.toString());
// Expected output: "foo"
  1. trim()
  • 作用:去掉字符串两端的空白字符
  • 语法:trim()
  • 返回值:新字符串
const greeting = '   Hello world!   ';
console.log(greeting);
// Expected output: "   Hello world!   ";
console.log(greeting.trim());
// Expected output: "Hello world!";
  1. trimEnd()
  • 作用:去掉字符串结尾的空白字符
  • 语法:trimEnd()
  • 返回值:新字符串
const greeting = '   Hello world!   ';
console.log(greeting);
// Expected output: "   Hello world!   ";
console.log(greeting.trimEnd());
// Expected output: "   Hello world!"
  1. trimStart()
  • 作用:去掉字符串开头的空白字符
  • 语法:trimStart()
  • 返回值:新字符串
const greeting = '   Hello world!   ';
console.log(greeting);
// Expected output: "   Hello world!   ";
console.log(greeting.trimStart());
// Expected output: "Hello world!   "
  1. valueOf()
  • 作用:返回 String 对象的字符串值,与toString()功能相同。此方法通常由 JavaScript 在内部调用,而不是在代码中显式调用
  • 语法:valueOf()
  • 返回值:字符串,String 对象的原始值
const stringObj = new String('foo');
console.log(stringObj);
// Expected output: String { "foo" }
console.log(stringObj.valueOf());
// Expected output: "foo"
  • 17
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值