If Else Conditionals within Function in JavaScript

Posted by Antoine-Laurent Lavoisier on Stack Overflow See other posts from Stack Overflow or by Antoine-Laurent Lavoisier
Published on 2013-11-09T15:34:21Z Indexed on 2013/11/09 15:53 UTC
Read the original article Hit count: 197

Filed under:

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/

© Stack Overflow or respective owner

Related posts about JavaScript