首页 > 解决方案 > 正则表达式匹配 / 和 .jsp 之间的字符串

问题描述

如果我做正则表达式匹配

str = "/mypage/account/info.jsp"
str.match('\/.*\.jsp')

我得到了整个字符串,但我只想获取“信息”

我怎样才能只使用正则表达式来完成?

标签: javascriptregex

解决方案


首先,你可以得到最后一个之后的文本/

/[^/]*$/

然后使用split得到想要的结果

const str = "/mypage/account/info.jsp";
const match = str.match(/[^/]*$/);

const result = match && match[0].split(".")[0];
console.log(result);

只有正则表达式

const str = "/mypage/account/info.jsp";
const match = str.match(/[^/]+(?=\.jsp$)/);

console.log(match[0]);


推荐阅读