---
layout: page
title: "JavaScript substr_compare function"
comments: true
sharing: true
footer: true
alias:
- /functions/view/substr_compare:790
- /functions/view/substr_compare
- /functions/view/790
- /functions/substr_compare:790
- /functions/790
---
<!-- Generated by Rakefile:build -->
A JavaScript equivalent of PHP's substr_compare

{% codeblock strings/substr_compare.js lang:js https://raw.github.com/kvz/phpjs/master/functions/strings/substr_compare.js raw on github %}
function substr_compare (main_str, str, offset, length, case_insensitivity) {
  // From: http://phpjs.org/functions
  // +   original by: Brett Zamir (http://brett-zamir.me)
  // +   derived from: strcasecmp, strcmp
  // *     example 1: substr_compare("abcde", "bc", 1, 2);
  // *     returns 1: 0
  if (!offset && offset !== 0) {
    throw 'Missing offset for substr_compare()';
  }

  if (offset < 0) {
    offset = main_str.length + offset;
  }

  if (length && length > (main_str.length - offset)) {
    return false;
  }
  length = length || main_str.length - offset;

  main_str = main_str.substr(offset, length);
  str = str.substr(0, length); // Should only compare up to the desired length
  if (case_insensitivity) { // Works as strcasecmp
    main_str = (main_str + '').toLowerCase();
    str = (str + '').toLowerCase();
    if (main_str == str) {
      return 0;
    }
    return (main_str > str) ? 1 : -1;
  }
  // Works as strcmp
  return ((main_str == str) ? 0 : ((main_str > str) ? 1 : -1));
}
{% endcodeblock %}

 - [Raw function on GitHub](https://github.com/kvz/phpjs/blob/master/functions/strings/substr_compare.js)

Please note that php.js uses JavaScript objects as substitutes for PHP arrays, they are 
the closest match to this hashtable-like data structure. 

Please also note that php.js offers community built functions and goes by the 
[McDonald's Theory](https://medium.com/what-i-learned-building/9216e1c9da7d). We'll put online 
functions that are far from perfect, in the hopes to spark better contributions. 
Do you have one? Then please just: 

 - [Edit on GitHub](https://github.com/kvz/phpjs/edit/master/functions/strings/substr_compare.js)

### Example 1
This code
{% codeblock lang:js example %}
substr_compare("abcde", "bc", 1, 2);
{% endcodeblock %}

Should return
{% codeblock lang:js returns %}
0
{% endcodeblock %}


### Other PHP functions in the strings extension
{% render_partial _includes/custom/strings.html %}
