js 找出最后一次字符串中指定或者某个字符后面出来的内容

发布时间 2023-12-30 13:47:34作者: simple-love

JS 获取最后一个 指定字符 后面的值
示例

let str = 'http://199.188.18.282:8012/logistics-web/rules/custom-rules'

1.找出’/'后面出来的值
使用 JavaScript 中的 .substring() 方法来实现

当然你也可以按的指定字符来截取

let str = 'http://199.188.18.282:8012/logistics-web/rules/custom-rules'
let index = str.lastIndexOf('/'); // 获取最后一个/的位置
let lastSegment = str.substring(index + 1); // 截取最后一个/后的值
console.log(lastSegment); // custom-rules

2.找出最后一次’/'后面出来的值
使用 JavaScript中的 .split() 方法和 .pop() 方法来实现

当然你也可以按的指定字符来截取

let str = 'http://199.188.18.282:8012/logistics-web/rules/custom-rules'
let lastSegment = str.split('/').pop();
console.log(lastSegment); // custom-rules

.split()方法会把字符串分割成数组,传入’/'则会把字符串以‘/’为分割点拆分成数组。
.pop() 方法会返回数组的最后一个元素。


3.找出倒数第二次’/'后面出来的值
使用 JavaScript中的 .substring() 方法和 .lastIndexOf() 方法来实现

let str = 'http://199.188.18.282:8012/logistics-web/rules/custom-rules'
// .lastIndexOf('/')找出最后一个 '/' 出现的位置,输出:45
let lastIndex = str.lastIndexOf('/');
// .substring(start, end) 从给定位置截取新字符串,输出:http://199.188.18.282:8012/logistics-web/rules
// 紧接着.lastIndexOf('/')找出最后一个 '/' 出现的位置,输出:39,在这个位置logistics-web/ 的索引
let secondLastIndex = str.substring(0, lastIndex).lastIndexOf('/');
// 最后让新字符串从倒数第二个'/'+1的位置到最后一个'/'的位置截取出来,就是结果了。
let secondLastSegment = str.substring(secondLastIndex + 1, lastIndex);
console.log(secondLastSegment); // rules

纯代码

let str = 'http://199.188.18.282:8012/logistics-web/rules/custom-rules'
let lastIndex = str.lastIndexOf('/');
let secondLastIndex = str.substring(0, lastIndex).lastIndexOf('/');
let secondLastSegment = str.substring(secondLastIndex + 1, lastIndex);
console.log(secondLastSegment); // rules

3.找出第五次’/'后面出来的值,来点长一点的
使用 JavaScript中的 .substring() 方法和 .lastIndexOf() 方法来实现

let str = 'http://199.188.18.282:8012/logistics-web/rules/custom-rules/XXXX/BBBB/HHHH'
let fifthSlashIndex = str.indexOf('/', str.indexOf('/', str.indexOf('/', str.indexOf('/', str.indexOf('/') + 1) + 1) + 1) + 1) + 1;
let sixthSlashIndex = str.indexOf('/', fifthSlashIndex + 1);
console.log(str.substring(fifthSlashIndex, sixthSlashIndex));

解释:使用 str.indexOf('/') 五次来找到第五次出现"/“的位置,str.indexOf(‘/’, fifthSlashIndex + 1) 来找到第六次”/“的位置,最后使用 str.substring(fifthSlashIndex, sixthSlashIndex) 来截取第五次”/"后面到第六次之间的字符。输出custom-rules
注意:如果第六次"/"不存在,那么 sixthSlashIndex 会返回-1,就不能使用substring来截取,所以在项目中使用提前判断一下