UNPKG

844 BJavaScriptView Raw
1// Copyright 2017-2022 @polkadot/util authors & contributors
2// SPDX-License-Identifier: Apache-2.0
3export const REGEX_HEX_PREFIXED = /^0x[\da-fA-F]+$/;
4export const REGEX_HEX_NOPREFIX = /^[\da-fA-F]+$/;
5/**
6 * @name isHex
7 * @summary Tests for a hex string.
8 * @description
9 * Checks to see if the input value is a `0x` prefixed hex string. Optionally (`bitLength` !== -1) checks to see if the bitLength is correct.
10 * @example
11 * <BR>
12 *
13 * ```javascript
14 * import { isHex } from '@polkadot/util';
15 *
16 * isHex('0x1234'); // => true
17 * isHex('0x1234', 8); // => false
18 * ```
19 */
20
21export function isHex(value, bitLength = -1, ignoreLength) {
22 return typeof value === 'string' && (value === '0x' || REGEX_HEX_PREFIXED.test(value)) && (bitLength === -1 ? ignoreLength || value.length % 2 === 0 : value.length === 2 + Math.ceil(bitLength / 4));
23}
\No newline at end of file