要找到字符串中第一个斜杠(/)前最后一次英文字母出现的位置,可以使用正则表达式配合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
}