ES6之字符串新增方法

本文详细介绍了ES6中字符串的新增方法,包括`String.fromCodePoint()`、`String.raw()`、`codePointAt()`、`normalize()`、`includes()`、`startsWith()`、`endsWith()`、`repeat()`、`padStart()`、`padEnd()`、`trimStart()`、`trimEnd()`、`matchAll()`和`replaceAll()`。这些方法扩展了字符串操作的功能,提升了开发效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. String.fromCodePoint()

String.fromCodePoint()静态方法返回使用指定的代码点序列创建的字符串。

语法

String.fromCodePoint(num1[,…[,numN]])
参数
num1,…,numN :一串Unicode编码位置,即“代码点”

说明

返回的是一个字符串

例子

      console.log(String.fromCodePoint(42)); //*
      console.log(String.fromCodePoint(65,90)); //AZ
      console.log(String.fromCodePoint(0x404)); //Є
      console.log(String.fromCodePoint(0x2F804)); //你 可获取两个字节也可获取四个字节
      console.log(String.fromCodePoint(194564)); //你
      console.log(String.fromCodePoint(0X1D306,0X61,0X1D307)); //𝌆a𝌇
      console.log(String.fromCodePoint('_')); //RangeError
      console.log(String.fromCodePoint(Infinity)); //RangeError
      console.log(String.fromCodePoint('-1')); //RangeError
      console.log(String.fromCodePoint(3.14)); //RangeError
      console.log(String.fromCodePoint(3e-2)); //RangeError
      console.log(String.fromCodePoint(NaN)); //RangeError

2. String.raw()

模板字符串的标签函数

语法

  1. String.raw(callSite,…substitutions):
  2. String.rawtemplateString;
    参数:
    callSite: 调用点对象 类似{ raw:[‘foo’,‘bar’]}
    …substitutions: 可选参数 内插表达式的值
    templateString :模板字符串 可包含占位符 ${…}

例子

      console.log(String.raw`Hi \\n ${2 + 3}`); //Hi \n 5
      console.log(String.raw`Hi \u000A.length`); //Hi \u000A.length
      console.log(String.raw({ raw: "test" }, 1, 2, 3)); //t1e2s3t
      console.log(String.raw({ raw: ['mony','happy','health'] }, 1, 2, 3)); //mony1happy2health

3. 实例方法:codePointAt()

codePointAt()方法返回一个Unicode编码点值的非负整数。

语法

str.codePointAt(pos)
参数:
pos 这个字符串需要转码的位置

例子

      console.log('ABC'.codePointAt(1)); //66
      console.log('\uD800\uDC00'.codePointAt(1)); //56320

      console.log('ABC'.codePointAt(3)); //undefined

4. 实例方法:normalize()

按指定Unicode 正规形式 将字符串正规化

语法

str.normalize([form]);
参数:
form : 可选
// “NFC” :规范分解,然后是规范组合。
// “NFD” :规范分解。
// “NFKC” :兼容性分解,然后是规范组合。
// “NFKD” :兼容性分解。

例子

      var str = "\u1E9B\u0323";
      console.log(str.normalize("NFC")); // "\u1E9B\u0323"
      
      console.log(str.normalize("NFD")); // "\u017F\u0323\u0307"

      console.log(str.normalize("NFKC")); // "\u1E69"

      console.log(str.normalize("NFKD")); // "\u0073\u0323\u0307"

5. 实例方法:includes(), startsWith(), endsWith()

includes():返回布尔值,表示是否找到参数字符串
startsWith():返回布尔值,表示参数字符串是否在原字符串头部
endsWith():返回布尔值,表示参数字符串是否在原字符串尾部

语法

str.endsWith(searchString[,length])
str.startWith(searchString[,position])
str.includes(searchString[,position])

例子

      var str = "To be, or not to be, that is the question.";

      alert(str.endsWith("question.")); // true
      alert(str.endsWith("to be")); // false
      alert(str.endsWith("to be", 19)); // true

      alert(str.startsWith("To be")); // true
      alert(str.startsWith("not to be")); // false
      alert(str.startsWith("not to be", 10)); // true
      
      console.log(str.includes("To be")); // true
      console.log(str.includes("question")); // true
      console.log(str.includes("nonexistent")); // false
      console.log(str.includes("To be", 1)); // false
      console.log(str.includes("TO BE")); // false

6. 实例方法:repeat()

返回一个新字符串,表示原字符串重复n次

语法

str.repeat(count)

例子

      // "abc".repeat(-1); RangeError: repeat count must be positive and less than inifinity
      console.log("abc".repeat(0)); //
      console.log("abc".repeat(1)); //abc
      console.log("abc".repeat(2)); //abcabc
      console.log("abc".repeat(3.9)); //abcabcabc 参数count将会被自动转换成整数.
      // "abc".repeat(1/0); RangeError: repeat count must be positive and less than inifinity
      console.log( ({toString:() => "abc" ,repeat:String.prototype.repeat}).repeat(2)); //abcabc,repeat是一个通用方法,也就是它的调用者可以不是一个字符串对象.

7. 实例方法:padStart(),padEnd()

padStart()用于头部补全,padEnd()用于尾部补全

语法

str.padStart()
str.padEnd()

例子

'abc'.padStart(10);         // "       abc"
'abc'.padStart(10, "foo");  // "foofoofabc"
'abc'.padStart(6,"123465"); // "123abc"
'abc'.padStart(8, "0");     // "00000abc"
'abc'.padStart(1);          // "abc"

'abc'.padEnd(10);          // "abc       "
'abc'.padEnd(10, "foo");   // "abcfoofoof"
'abc'.padEnd(6, "123456"); // "abc123"
'abc'.padEnd(1);           // "abc"

8. 实例方法:trimStart(),trimEnd()

trimStart()消除字符串头部的空格,trimEnd()消除尾部的空格。

语法

str.trimStart();
str.trimEnd();
返回一个新字符串

例子

var str = "   foo  ";

console.log(str.length); // 8

str = str.trimStart()    // 等同于 str = str.trimLeft();
console.log(str.length); // 5
console.log(str);        // "foo  "

str = str.trimRight();  // 或写成str = str.trimEnd();
console.log(str.length); // 6
console.log(str);       // '   foo'

9. 实例方法:matchAll()

matchAll()方法返回一个所有匹配正则表达式的结果

语法

str.matchAll(regexp)

例子

const regexp = RegExp('foo[a-z]*','g');
const str = 'table football, foosball';
const matches = str.matchAll(regexp);

for (const match of matches) {
  console.log(`Found ${match[0]} start=${match.index} end=${match.index + match[0].length}.`);
}
// expected output: "Found football start=6 end=14."
// expected output: "Found foosball start=16 end=24."

// matches iterator is exhausted after the for..of iteration
// Call matchAll again to create a new iterator
Array.from(str.matchAll(regexp), m => m[0]);
// Array [ "football", "foosball" ]

10.实例方法:replaceAll()

一次性替换所有匹配

语法

const newStr = str.replaceAll(regexp|substr,newSubstr|function)
注:当使用一个 regex时,您必须设置全局(“ g”)标志,
否则,它将引发 TypeError:“必须使用全局 RegExp 调用 replaceAll”。

例子

'aabbcc'.replaceAll('b','.');
//'aa..cc'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值