首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

string.codePointAt

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

语法

代码语言:javascript
复制
str.codePointAt(pos)

参数

pos这个字符串中需要转码的元素的位置。

返回值

返回值是在字符串中的给定索引的编码单元体现的数字,如果在索引处没找到元素则返回?undefined

描述

如果在指定的位置没有元素则返回?undefined?。如果在索引处开始没有UTF-16 代理对,将直接返回在那个索引处的编码单元。

Surrogate Pair是UTF-16中用于扩展字符而使用的编码方式,是一种采用四个字节(两个UTF-16编码)来表示一个字符,称作代理对。

Examples

Using codePointAt()

代码语言:javascript
复制
'ABC'.codePointAt(1);          // 66
'\uD800\uDC00'.codePointAt(0); // 65536

'XYZ'.codePointAt(42); // undefined

Polyfill

给原生不支持 ECMAScript 6 的浏览器使用codePointAt()方法的的一个字符串扩展方法。

代码语言:javascript
复制
/*! http://mths.be/codepointat v0.1.0 by @mathias */
if (!String.prototype.codePointAt) {
  (function() {
    'use strict'; // needed to support `apply`/`call` with `undefined`/`null`
    var codePointAt = function(position) {
      if (this == null) {
        throw TypeError();
      }
      var string = String(this);
      var size = string.length;
      // `ToInteger`
      var index = position ? Number(position) : 0;
      if (index != index) { // better `isNaN`
        index = 0;
      }
      // Account for out-of-bounds indices:
      if (index < 0 || index >= size) {
        return undefined;
      }
      // Get the first code unit
      var first = string.charCodeAt(index);
      var second;
      if ( // check if it’s the start of a surrogate pair
        first >= 0xD800 && first <= 0xDBFF && // high surrogate
        size > index + 1 // there is a next code unit
      ) {
        second = string.charCodeAt(index + 1);
        if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate
          // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
          return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
        }
      }
      return first;
    };
    if (Object.defineProperty) {
      Object.defineProperty(String.prototype, 'codePointAt', {
        'value': codePointAt,
        'configurable': true,
        'writable': true
      });
    } else {
      String.prototype.codePointAt = codePointAt;
    }
  }());
}

规范

Specification

Status

Comment

ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'String.prototype.codePointAt' in that specification.

Standard

Initial definition.

ECMAScript Latest Draft (ECMA-262)The definition of 'String.prototype.codePointAt' in that specification.

Living Standard

?

浏览器兼容性

Feature

Chrome

Edge

Firefox

Internet Explorer

Opera

Safari

Basic Support

41

(Yes)

29

No

28

10

Feature

Android

Chrome for Android

Edge mobile

Firefox for Android

IE mobile

Opera Android

iOS Safari

Basic Support

(Yes)

(Yes)

(Yes)

29

No

(Yes)

10

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com