获取以特定字符为起始点的字符的序号索引(ascii码值)

Code:

/**
 * 返回目标字符在特定范围内(有特定起始点)的序号索引
 * @param {string} target - 目标字符
 * @param {string} startChar - 起始字符(可以传入一个字符串,但只以头一个字符为标准)
 * @return {number} 
 */
var getCharRangeIndex = function(target, startChar = 'a') {
  if (typeof startChar !== 'string' || startChar.length === 0) {
    startChar = 'a';
  }
  if (typeof target !== 'string' || target.length !== 1) {
    throw new TypeError('TypeError:请输入字符串形式的有效参数!')
  }
  const startCharCode = startChar.charCodeAt(0);
  return target.charCodeAt(0) - startCharCode;
};

 

示例:

getCharRangeIndex('x'); // 23
getCharRangeIndex('z'); // 25
getCharRangeIndex('G', 'A'); // 6
getCharRangeIndex('G', 'AB'); // 6
getCharRangeIndex(1, 'A'); // Error

 

posted @ 2023-05-06 12:24  樊顺  阅读(18)  评论(0编辑  收藏  举报