PHP's substr_compare in JavaScript

How to use

You you can install via yarn add locutus and require this function via const substr_compare = require('locutus/php/strings/substr_compare').

It is important to use a bundler that supports tree-shaking so that you only ship the functions that you actually use to your browser, instead of all of Locutus, which is massive. Examples are: Parcel, webpack, or rollup.js. For server-side use this is typically less of a concern.

Examples

Please note that these examples are distilled from test cases that automatically verify our functions still work correctly. This could explain some quirky ones.

#codeexpected result
1substr_compare("abcde", "bc", 1, 2)0

Here’s what our current JavaScript equivalent to PHP's substr_compare looks like.

module.exports = function substr_compare(mainStr, str, offset, length, caseInsensitivity) {
// discuss at: https://locutus.io/php/substr_compare/
// original by: Brett Zamir (https://brett-zamir.me)
// original by: strcasecmp, strcmp
// example 1: substr_compare("abcde", "bc", 1, 2)
// returns 1: 0

if (!offset && offset !== 0) {
throw new Error('Missing offset for substr_compare()')
}

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

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

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

A community effort

Not unlike Wikipedia, Locutus is an ongoing community effort. Our philosophy follows The McDonald’s Theory. This means that we assimilate first iterations with imperfections, hoping for others to take issue with-and improve them. This unorthodox approach has worked very well to foster fun and fruitful collaboration, but please be reminded to use our creations at your own risk. THE SOFTWARE IS PROVIDED "AS IS" has never been more true than for Locutus.

Now go and: [ View on GitHub | Edit on GitHub | View Raw ]


« More PHP strings functions


Star