UNPKG

1.12 kBJavaScriptView Raw
1import _typeof from 'babel-runtime/helpers/typeof';
2/**
3 * Generate a string to be used for HTML id attributes
4 *
5 * @param {String} prefix - prefix text for the id. Important because without one, eventually there will be 2 elements with the same id on the same page
6 * @param {Number} max - range for the random number generator. Defaults to 1,000,000, but can be set higher if necessary.
7 * @returns {String}
8 */
9export function randomId(prefix) {
10 var max = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1000000;
11
12 var rand = Math.ceil(Math.random() * max);
13
14 return prefix ? escapeForId(prefix) + '-' + rand : rand.toString(10);
15}
16
17/**
18 * Replace characters not allowed for HTML id attributes
19 *
20 * @param {String} text
21 * @returns {String}
22 */
23export function escapeForId(text) {
24 if (!text) {
25 return '';
26 }
27
28 if ((typeof text === 'undefined' ? 'undefined' : _typeof(text)) === 'object') {
29 text = JSON.stringify(text);
30 } else if (typeof text !== 'string') {
31 text = String(text);
32 }
33
34 return text.replace(/['"]/gm, '').replace(/[\s'"]/gm, '-');
35}
\No newline at end of file