0

I'd like to use .indexOf to search between a range of characters in text submitted by a user, but I'm not sure how I would go about it.

Let's say: myText = "abcd" and I wanted to search to see if the "ab" existed ONLY at the start, and ONLY up to the 2nd character.

if "ab" is present within the first 2 characters, then "do stuff"

If myText = "abab" I would only want it to recognize the 1st "ab" and execute a command based on that.

I would then like to search between the 3rd and 4th character within another indexOf command. etc.

so far I'm only able to do the following:

myText = "abab"
if (myText.indexOf("ab") > -1) alert("Found first 'ab'");

Any ideas?

4

2 回答 2

2

要测试字符串开头的子字符串,您可以测试它是否0正好在索引处:

if (myText.indexOf("ab") === 0) {
    // starts with "ab"
}

ab在其中,您可以通过在索引处开始搜索来测试第二个,2并期望它也在那里:

// ...
    if (myText.indexOf("ab", 2) === 2) {
        // followed by "ab"
    }
// ...

示例:http: //jsfiddle.net/j7Kmt/

于 2013-08-11T09:32:09.933 回答
0

考虑这个例子

"Blue Whale".indexOf("Blue");     // returns  0
"Blue Whale".indexOf("Blute");    // returns -1
"Blue Whale".indexOf("Whale", 0); // returns  5
"Blue Whale".indexOf("Whale", 5); // returns  5
"Blue Whale".indexOf("", 9);      // returns  9
"Blue Whale".indexOf("", 10);     // returns 10
"Blue Whale".indexOf("", 11);     // returns 10
"Blue Whale".indexOf("ue", 0);     // returns 2

这里第一个参数是character您要查找的索引,第二个是要查找的起始索引character

在您的情况下,检查如下:

myText = "abab"
if (myText.indexOf("ab") == 0) alert("Found first 'ab'");
于 2013-08-11T09:33:43.250 回答