简体   繁体   中英

Javascript: matching a dynamic string against an array

I'm attempting to teach myself javascript. I chose something I assumed was simple, but ran into problems relatively quickly.

I'm attempting to search a string for another string given by the user.

My code so far is:

var source = "XREs2qqAQfjr6NZs6H5wkZdOES5mikexRkOPsj6grQiYNZfFoqXI4Nnc1iONKVrA";
var searchString = []; //the users input
searchString = prompt("Enter search string");
var hits = [];
var one = 0;
var two = 0;
var k = 0;

var sourceSearch = function(text) {
    for(i = 0; i < source.length; i++) { //for each character in the source
        if(source[i] === searchString[0]) {  //if a character in source matches the first element in the users input
            one  = source.indexOf(i); //confused from here on
            for(p = searchString.length; p > 0; p--) {

            }                    
        }
    }
};


sourceSearch(searchString);

My idea was:

  • check to see if the first loop finds a character that matches the first character in the user input
  • if it matches, check to see if the next X characters after the first match the next X characters in the source string
  • if they all match, push them to the hits array

My problem: I have no idea how to iterate along the arrays without nesting quite a few if statements, and even then, that wouldn't be sufficient, considering I want the program to work with any input.

Any ideas would be helpful. Thanks very much in advance.

Note: There are a few un-used variables from ideas I was testing, but I couldn't make them work.

You can try:

if (source.indexOf(searchString) !== -1) {
// Match!
}
else
{
//No Match!
}

to follow your approach, you can just play with 2 indexes:

var sourceSearch = function(text) {
    j = 0;
    for(i = 0; i < source.length; i++) {
        if(source[i] === text[j]) {
            j++;                   
        } else {
            j = 0;
        }
        if (j == text.length) {
            console.log(i - j); //this prints the starting index of the matching substring
        }
    }
};

As the other answers so far point out, JavaScript strings have an indexOf function that does what you want. If you want to see how it's done "by hand", you can modify your function like this:

var sourceSearch = function(text) {
    var i, j, ok; // always declare your local variables. globals are evil!
    // for each start position
    for(i = 0; i < source.length; i++) {
        ok = true;
        // check for a match
        for (j = searchString.length - 1; ok && j >= 0; --j) {
            ok = source[i + j] === searchString[j];
        }
        if (ok) {
            // searchString found starting at index i in source
        }
    }
};

This function will find all positions in source at which searchString was found. (Of course, you could break out of the loop on the first success.) The logic is to use the outer loop to advance to each candidate start position in source and use the inner loop to test whether that position actually is the position of a match to searchString .

This is not the best algorithm for searching strings. The built-in algorithm is much faster (both because it is a better algorithm and because it is native code).

These answers are all pretty good, but I'd probably opt for something like this:

var source = "XREs2qqAQfjr6NZs6H5wkZdOES5mikexRkOPsj6grQiYNZfFoqXI4Nnc1iONKVrA";
var searchString = []; //the users input
searchString = prompt("Enter search string");
var hits = source.split(searchString);
var hitsCount = hits.length - 1;

This way you have all of the data you need to figure out where each hit occurred in he source, if that's important to you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM