string.codePointAt
string.codePointAt
codePointAt()
方法返回 一个 Unicode 编码点值的非负整数。
语法
str.codePointAt(pos)
参数
pos
这个字符串中需要转码的元素的位置。
返回值
返回值是在字符串中的给定索引的编码单元体现的数字,如果在索引处没找到元素则返回 undefined
。
描述
如果在指定的位置没有元素则返回 undefined
。如果在索引处开始没有UTF-16 代理对,将直接返回在那个索引处的编码单元。
Examples
Using codePointAt()
'ABC'.codePointAt(1 // 66
'\uD800\uDC00'.codePointAt(0 // 65536
'XYZ'.codePointAt(42 // undefined
Polyfill
给原生不支持 ECMAScript 6 的浏览器使用codePointAt()
方法的的一个字符串扩展方法。
/*! 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 |