获取以特定字符为起始点的字符的序号索引(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 @   樊顺  阅读(27)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 【杂谈】分布式事务——高大上的无用知识?
点击右上角即可分享
微信分享提示