JavaScript字符串API


JavaScript 字符串 API 列表

API 描述
at() 方法接受一个整数值,并返回一个新的 String,该字符串由位于指定偏移量处的单个 UTF-16 码元组成。该方法允许正整数和负整数。负整数从字符串中的最后一个字符开始倒数。
charAt() 返回一个由给定索引处的单个 UTF-16 码元构成的新字符串符,如果 index 超出了 0 – str.length - 1 的范围,charAt() 将返回一个空字符串

at

MDN 资料

const sentence = "The quick brown fox jumps over the lazy dog.";

let index = 5;

console.log(
  `Using an index of ${index} the character returned is ${sentence.at(index)}`
);
// Expected output: "Using an index of 5 the character returned is u"

index = -4;

console.log(
  `Using an index of ${index} the character returned is ${sentence.at(index)}`
);
// Expected output: "Using an index of -4 the character returned is d"

charAt

MDN 资料

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"

文章作者: XIAKEMING-侠客明
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 XIAKEMING-侠客明 !
评论