首页 > 解决方案 > Javascript在两个相同字符之间获得subsring?

问题描述

我正在尝试从两个相同字符之间存在的另一个字符串中提取一个子字符串。

这是我的整个字符串:

abcdefg?hijk?lmnop

这是我要提取的子字符串:

abcdefg? hijk lmnop

_

我尝试使用此代码:

currenturl.substring(currenturl.lastIndexOf("?") + 1, currenturl.lastIndexOf("?"));

但它只返回“?”

感谢您的任何建议!

标签: javascriptstringsubstring

解决方案


您应该使用indexOfwhich 返回第一个匹配的索引?作为第一个参数subString

const currenturl = "abcdefg?hijk?lmnop";
const result = currenturl.substring(currenturl.indexOf("?") + 1, currenturl.lastIndexOf("?"));

console.log(result);


推荐阅读