js实现php strpos函数

* strpos.js

function strpos(haystack, needle, start) {
    if (typeof(start)==="undefined") {
	start = 0;
    }
    if (!needle) {
	return 0;
    }
    var j = 0;
    for (var i = start; i < haystack.length && j < needle.length; i++) {
	if (haystack.charAt(i) === needle.charAt(j)) {
	    j++;
	} else {
	    j = 0;
	}
    }
    if (j === needle.length) {
	return i - needle.length;
    }
    return -1;
}

找不到返回-1 不是false

 

php写法:

    public static function pos($haystack, $needle, $start = 0) {
        if (!$needle) {
            return 0;
        }
        $j = 0;
        $m = strlen($haystack);
        $n = strlen($needle);
        for ($i = $start; $i < $m && $j < $n; $i++) {
            if ($haystack[$i] === $needle[$j]) {
                $j += 1;
            } else {
                $j = 0;
            }
        }
        if ($j === $n) {
            return $i - $n;
        }
        return -1;
    }

 

你可能感兴趣的:(javascript)