質問

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?

役に立ちましたか?

解決

To test for the substring at the start of the string, you can test if it's at index 0 exactly:

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

Within that, you can test for the 2nd ab by starting that search at index 2 and expect it there as well:

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

Example: http://jsfiddle.net/j7Kmt/

他のヒント

Consider this example

"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

Here first parameter is character you want to find index of and second is starting index to find that character

In your case check like this:

myText = "abab"
if (myText.indexOf("ab") == 0) alert("Found first 'ab'");
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top