JavaScript或jQuery相当于PHP的strstr()函数

在jQuery或JavaScript中是否有与PHP中的strstr()相同的函数?

我有一个应该是1,2,3,12,13,23或123的AJAX响应。我想检查1是否存在,然后如果2存在则则存在3。

试试这个:

 function strstr(haystack, needle, bool) { // Finds first occurrence of a string within another // // version: 1103.1210 // discuss at: http://phpjs.org/functions/strstr // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + bugfixed by: Onno Marsman // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // * example 1: strstr('Kevin van Zonneveld', 'van'); // * returns 1: 'van Zonneveld' // * example 2: strstr('Kevin van Zonneveld', 'van', true); // * returns 2: 'Kevin ' // * example 3: strstr('name@example.com', '@'); // * returns 3: '@example.com' // * example 4: strstr('name@example.com', '@', true); // * returns 4: 'name' var pos = 0; haystack += ""; pos = haystack.indexOf(needle); if (pos == -1) { return false; } else { if (bool) { return haystack.substr(0, pos); } else { return haystack.slice(pos); } } } 

(来自http://phpjs.org/functions/strstr:551 )

整体phpjs非常惊人。

好的,我发现了一些有效的东西!

http://my-sliit.blogspot.com/2008/06/search-string-javascript-like-strstr-in.html

谢谢你的贡献:)

阅读这些javascript函数 – indexOF()和lastIndexOf()。

好吧,没有内置String.indexOf( String str )返回子字符串的整数索引但是,你可以轻松地构建一个: http : //aimtb.wordpress.com/2011/03/16/strstr-in-javascript /

 function strstr(haystack, needle, bool) { // Finds first occurrence of a string within another // // version: 1103.1210 // discuss at: http://phpjs.org/functions/strstr // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + bugfixed by: Onno Marsman // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // * example 1: strstr('Kevin van Zonneveld', 'van'); // * returns 1: 'van Zonneveld' // * example 2: strstr('Kevin van Zonneveld', 'van', true); // * returns 2: 'Kevin ' // * example 3: strstr('name@example.com', '@'); // * returns 3: '@example.com' // * example 4: strstr('name@example.com', '@', true); // * returns 4: 'name' var pos = 0; haystack += ""; pos = haystack.indexOf(needle); if (pos == -1) { return false; } else { if (bool) { return haystack.substr(0, pos); } else { return haystack.slice(pos); } } } 

这是一个没有任何库/方法调用的实现:

 function strstr (haystack, needle) { var i = 0, tempLength = 0, temp = []; for (;;) { if (haystack[i] === undefined || needle == null) { return "No match"; } //if the char doesn't match then reset else if (haystack[i] !== needle[tempLength]) { temp = []; tempLength = 0; } //the char matches so let's store it. else if (haystack[i] === needle[tempLength]) { temp[tempLength] = haystack[i]; if (needle[tempLength + 1] === undefined) { return temp; } tempLength++; } i++; } };