1

need help checking if a text contains a string to search for.

Say that I have a text

"somerandomtextstringexampleexample_1"

And I want to compare with for example this String

"example_1_e23wet_est1"

Now because the text contains "example_1" I want the function to return "example_1" and not also "example". (But if the string would have been "example_4_e23wet_est1" it should have returned just "example)

So the function takes 2 arguments

function searchForString(text,stringToCompare){
var foundstring;
...
if(foundstring)
return foundstring//In this case "example_1"
}

But then I'm pretty lost on how to carry on here since "indexOf" don't work here.

Thanks in advance =)

2
  • You said: But if the string would have been "example_4_e23wet_est1" it should have returned just "example" . Shouldn't it have been "example_"? What you actually want is the largest substring of 2 strings right? Commented Jul 8, 2011 at 16:13
  • I think the problem that you are having is that your rules around what should match are very vague - for example what if your second string was example_1somerando? You should precisely define the rules for your function and then have another go. Commented Jul 8, 2011 at 16:15

2 Answers 2

1

Well if you want the largest common substring, you might want to have a look here : largest common substring implementation and at this discussion about suffix tree for that matter :)

Sign up to request clarification or add additional context in comments.

Comments

0

Call searchForString("somerandomtextstringexampleexample_1", "example_1_e23wet_est1");

It returns a list of matches. For example in this case: ["e", "ex", "example", "e", "example_1", "e"]... Take the greatest.

function searchForString(text, searchString) {
    var i, max, match = '', matches = [], str;

    function matchingStr(string, searchString) {
        var i = 0, 
            j = 0, 
            matchStr = '',
            strLength = string.length,
            sstrLength = searchString.length;

        while (string[i] === searchString[j] &&
               i < strLength &&
               j < sstrLength) {

            matchStr += string[i];
            i++;
            j++;
        }

        return matchStr;
    }

    for (i = 0, max = text.length; i < max; i++) {
        str = (i === 0) ? text : text.slice(i, max);
        console.log("str: " + str);
        console.log(match);
        match = matchingStr(str, searchString);    

        if (match.length !== 0) {
            matches.push(match);
        }         
    }    
  return matches;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.