js 字符串 第一个斜杠前最后一次出现英文字母的位置并添加自定义值,返回新值

本文介绍了如何使用JavaScript的正则表达式和lastIndexOf方法找到字符串中斜杠前的最后一个英文字母索引,以及如何扩展该功能在遇到数字时插入内容。
摘要由CSDN通过智能技术生成

要找到字符串中第一个斜杠(/)前最后一次英文字母出现的位置,可以使用正则表达式配合lastIndexOf方法。以下是实现这一功能的示例代码: 如果是匹配第一个数字前的字母加值可以看这里

function findLastLetterIndexBeforeSlash(str) {
  const lastSlashIndex = str.lastIndexOf('/');
  const regex = /[A-Za-z]/;
  for (let i = lastSlashIndex - 1; i >= 0; i--) {
    if (regex.test(str[i])) {
      return i;
    }
  }
  return -1; // 如果没有找到英文字母,则返回-1
}
 
const str = 'ZDD222G18/18/521a';
const index = findLastLetterIndexBeforeSlash(str);
console.log(index); // 输出英文字母位置的索引
VM5772:14 6
undefined
function findLastLetterIndexBeforeSlash(str) {
  const lastSlashIndex = str.lastIndexOf('/');
  const regex = /[A-Za-z]/;
  for (let i = lastSlashIndex - 1; i >= 0; i--) {
    if (regex.test(str[i])) {
      return i;
    }
  }
  return -1; // 如果没有找到英文字母,则返回-1
}
 
const str = 'ZDDG18/18/521a';
const index = findLastLetterIndexBeforeSlash(str);
console.log(index); // 输出英文字母位置的索引

这段代码定义了一个函数findLastLetterIndexBeforeSlash,它接受一个字符串参数并返回斜杠(/)前最后一次英文字母出现的位置的索引。如果没有找到英文字母,则返回-1。
在这里插入图片描述
然后可以组装我们想要的数据
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

方法处理封装

const insertAtFirstDigit = (str: any, contentToInsert: any) => {
  let index = indexChange(str)
  // 如果没有找到数字,直接返回原字符串
  if (index === -1) {
    return str
  }
  // 使用 slice 方法插入内容
  return str.slice(0, index+1) + contentToInsert + str.slice(index+1)
}
const indexChange = (str:any) =>{
  const lastSlashIndex = str.lastIndexOf('/');
  const regex = /[A-Za-z]/;
  for (let i = lastSlashIndex - 1; i >= 0; i--) {
    if (regex.test(str[i])) {
      return i;
    }
  }
  return -1; // 如果没有找到英文字母,则返回-1
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值