[英]Find indexOf character after certain index
Pretty basic but I'm afraid I'm overlooking a simple solution. 很基本,但恐怕我忽略了一个简单的解决方案。 I have the following string ... IBAN: NL56INGB06716xxxxx ...
我有以下字符串... IBAN: NL56INGB06716xxxxx ...
I need the accountnumber so I'm looking for indexOf("IBAN: ")
but now I need to find the next space/whitespace char after that index. 我需要帐号,所以我正在寻找indexOf("IBAN: ")
但是现在我需要在该索引之后找到下一个空格/空白字符。
I don't really think I would need a loop for this but it's the best I can come up with. 我真的不认为我需要为此循环,但这是我能想到的最好的循环。 Regex capture group maybe better? 正则表达式捕获组可能更好? How would I do that? 我该怎么做?
From MDN String.prototype.indexOf
来自MDN String.prototype.indexOf
str.indexOf(searchValue[, fromIndex])
fromIndex
Optional.fromIndex
可选。 The location within the calling string to start the search from. 调用字符串中开始搜索的位置。 It can be any integer. 它可以是任何整数。 The default value is0
. 默认值为0
。
nb .indexOf
will only look for a specific substring, if you want to find a choice from many characters, you will either need to loop and compare or use RegExp nb .indexOf
将仅查找特定的子字符串,如果要从多个字符中选择一个选项,则需要循环比较并使用RegExp
Gracious example 亲切的例子
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"
While you can pass a starting index as Paul suggested, it would seem that a simple regex may just be easier. 尽管您可以按照Paul的建议传递起始索引,但似乎简单的正则表达式可能会更容易。
var re = /IBAN:\s*(\S+)/
The capture group will hold the sequence of non-whitespace characters after the IBAN:
捕获组将在IBAN:
之后保留非空白字符的序列IBAN:
var match = re.exec(my_str)
if (match) {
console.log(match[1]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.