在某个索引之后查找字符的索引

Find indexOf character after certain index

本文关键字:索引 字符 查找 之后      更新时间:2023-09-26

非常基本,但恐怕我忽略了一个简单的解决方案。我有以下字符串... IBAN: NL56INGB06716xxxxx ...

我需要帐号,所以我正在寻找indexOf("IBAN: ")但现在我需要找到该索引之后的下一个空格/空格字符。

真的不认为我需要一个循环,但这是我能想到的最好的。正则表达式捕获组可能更好?我该怎么做?

来自MDN String.prototype.indexOf

str.indexOf(searchValue[, fromIndex])

fromIndex自选。调用字符串中要从中开始搜索的位置。它可以是任何整数。默认值为 0

:注: .indexOf只会查找特定的子字符串,如果您想从许多字符中找到选择,则需要循环和比较或使用 RegExp

<小时 />

优雅的例子

var haystack = 'foo_ _IBAN: Bar _ _';
var needle = 'IBAN: ',
    i = haystack.indexOf(needle),
    j;
if (i === -1) {
    // no match, do something special
    console.warn('One cannot simply find a needle in a haystack');
}
j = haystack.indexOf(' ', i + needle.length);
// now we have both matches, we can do something fancy
if (j === -1) {
    j = haystack.length; // no match, set to end?
}
haystack.slice(i + needle.length, j); // "Bar"

虽然你可以按照保罗的建议传递起始索引,但似乎一个简单的正则表达式可能更容易。

var re = /IBAN:'s*('S+)/

捕获组将在IBAN:之后保存非空格字符序列

var match = re.exec(my_str)
if (match) {
    console.log(match[1]);
}