0

I'm having issues with conditionals. I want to return the index where pattern starts in string (or -1 if not found). The search is to be case sensitive if the 3rd parameter is true otherwise it is case insensitive.

Examples
index("abAB12","AB",true) returns 2 but index("abAB12","AB",false) returns 0
index("abAB12","BA",true) returns -1 and index("abAB12","BA",false) returns 1

Any idea how I can accomplish this?

This is my code so far

var s = "abAB12"
var p = "AB"
var cs = true

    function index(string, pattern, caseSensitive) {

        if (pattern) {

            var found = false;

            if (caseSensitive = false) {
                if (string.indexOf(pattern.) >= 0) {
                    found = true;
                }
                return (found);
                else {
                    return ("");
                }
            } else if (caseSensitive = true) {
                if (string.toLowerCase().indexOf(pattern.toLowerCase()) >= 0) {
                    found = true;
                }
                return (found);
            } else {
                return ("");
            }
        }

    }

alert(index(s, p, cs));

Fiddle at http://jsfiddle.net/AfDFb/1/

5 Answers 5

2

You have some mistype in your code. On the 15th line you have

}
return (found);
else {

This is not not valid. Change it to

return (found);
}
else {

There is another one.

if (caseSensitive = false) {

= used for assignment. You need to use == in if statements when comparing. Also on the 13th line, there's an extra . after pattern. Remove it.

if (string.indexOf(pattern.) >= 0) {

Your fiddle example

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

Comments

2

You can use string.search() with a regular expression to accomplish this in one liner:

function index(input, key, caseMatters) {
    return input.search(new RegExp(key, caseMatters ? '' : 'i'));
}

Now you can:

index("abAB12","AB",true); // returns 2
index("abAB12","AB",false); // returns 0
index("abAB12","BA",true); // returns -1
index("abAB12","BA",false); // returns 1

Comments

0

You need to use double equals sign == in your if, else statements.

if(caseSensitive == false)

And

if(caseSensitive == true)

Comments

0

You are assigning value inside if condition instead of comparing it.

Try

 if (caseSensitive == false) {

and

 if(caseSensitive == true)

Comments

0

You'd better use search :

'abAB12'.search(/AB/); // 2
'abAB12'.search(/AB/i); // 0
'abAB12'.search(/BA/); // -1
'abAB12'.search(/BA/i); // 1

The i flag means "case insensitive" ( insensible à la casse :D ).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.