phpjavascriptphpjs

JavaScript equivalent of PHP's strpbrk function?


In PHP, I can use the strpbrk function to determine if a certain string contains a certain set of characters. Is there a way to do that in JavaScript?

TIA.

Edit: for those who may know JS but not PHP, strpbrk takes an input string and a string containing what you want to match as its arguments, and returns a string starting from the first character found if a match if found, or false if one isn't.


Solution

  • See here: Javascript equivalent for PHP's strpbrk

    function strpbrk (haystack, char_list) {
      // http://kevin.vanzonneveld.net
      // +   original by: Alfonso Jimenez (http://www.alfonsojimenez.com)
      // +   bugfixed by: Onno Marsman
      // +    revised by: Christoph
      // +    improved by: Brett Zamir (http://brett-zamir.me)
      // *     example 1: strpbrk('This is a Simple text.', 'is');
      // *     returns 1: 'is is a Simple text.'
      for (var i = 0, len = haystack.length; i < len; ++i) {
        if (char_list.indexOf(haystack.charAt(i)) >= 0) {
          return haystack.slice(i);
        }
      }
      return false;
    }