PHP's ord in TypeScript

✓ Verified: PHP 8.3
Examples tested against actual runtime. CI re-verifies continuously. Only documented examples are tested.
Rosetta Stone: perl/ord

How to use

Install via yarn add locutus and import: import { ord } from 'locutus/php/strings/ord'.

Or with CommonJS: const { ord } = require('locutus/php/strings/ord')

Use a bundler that supports tree-shaking so you only ship the functions you actually use. Vite, webpack, Rollup, and Parcel all handle this. For server-side use this is less of a concern.

Examples

These examples are extracted from test cases that automatically verify our functions against their native counterparts.

#codeexpected result
1ord('K')75

Notes

  • Unlike PHP (which returns 0-255), this implementation supports Unicode code points via surrogate pairs

Here's what our current TypeScript equivalent to PHP's ord looks like.

export function ord(string: string): number {
// discuss at: https://locutus.io/php/ord/
// parity verified: PHP 8.3
// original by: Kevin van Zonneveld (https://kvz.io)
// bugfixed by: Onno Marsman (https://twitter.com/onnomarsman)
// improved by: Brett Zamir (https://brett-zamir.me)
// input by: incidence
// note 1: Unlike PHP (which returns 0-255), this implementation
// note 1: supports Unicode code points via surrogate pairs
// example 1: ord('K')
// returns 1: 75

const str = string + ''
const code = str.charCodeAt(0)

if (code >= 0xd800 && code <= 0xdbff) {
// High surrogate (could change last hex to 0xDB7F to treat
// high private surrogates as single characters)
const hi = code
if (str.length === 1) {
// This is just a high surrogate with no following low surrogate,
// so we return its value;
return code
// we could also throw an error as it is not a complete character,
// but someone may want to know
}
const low = str.charCodeAt(1)
return (hi - 0xd800) * 0x400 + (low - 0xdc00) + 0x10000
}
if (code >= 0xdc00 && code <= 0xdfff) {
// Low surrogate
// This is just a low surrogate with no preceding high surrogate,
// so we return its value;
return code
// we could also throw an error as it is not a complete character,
// but someone may want to know
}

return code
}

Improve this function

Locutus is a community effort following The McDonald's Theory: we ship first iterations, hoping others will improve them. If you see something that could be better, we'd love your contribution.

View on GitHub · Edit on GitHub · View Raw


« More PHP strings functions


Star