PHP's strrev in JavaScript

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

module.exports = function strrev (string) {
// discuss at:
// original by: Kevin van Zonneveld (
// bugfixed by: Onno Marsman (
// reimplemented by: Brett Zamir (
// example 1: strrev('Kevin van Zonneveld')
// returns 1: 'dlevennoZ nav niveK'
// example 2: strrev('a\u0301haB')
// returns 2: 'Baha\u0301' // combining
// example 3: strrev('A\uD87E\uDC04Z')
// returns 3: 'Z\uD87E\uDC04A' // surrogates
// test: 'skip-3'
string = string + ''
// Performance will be enhanced with the next two lines of code commented
// out if you don't care about combining characters
// Keep Unicode combining characters together with the character preceding
// them and which they are modifying (as in PHP 6)
// See (Me+Mn)
// We also add the low surrogate range at the beginning here so it will be
// maintained with its preceding high surrogate
const chars = [
const graphemeExtend = new RegExp('(.)([' + chars.join('') + ']+)', 'g')
// Temporarily reverse
string = string.replace(graphemeExtend, '$2$1')
return string.split('').reverse().join('')
[ View on GitHub | Edit on GitHub | Source on GitHub ]

How to use

You you can install via npm install locutus and require it via require('locutus/php/strings/strrev'). You could also require the strings module in full so that you could access strings.strrev instead.

If you intend to target the browser, you can then use a module bundler such as Parcel, webpack, Browserify, or rollup.js. This can be important because Locutus allows modern JavaScript in the source files, meaning it may not work in all browsers without a build/transpile step. Locutus does transpile all functions to ES5 before publishing to npm.

A community effort

Not unlike Wikipedia, Locutus is an ongoing community effort. Our philosophy follows The McDonald’s Theory. This means that we don't consider it to be a bad thing that many of our functions are first iterations, which may still have their fair share of issues. We hope that these flaws will inspire others to come up with better ideas.

This way of working also means that we don't offer any production guarantees, and recommend to use Locutus inspiration and learning purposes only.


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
1strrev('Kevin van Zonneveld')'dlevennoZ nav niveK'
2strrev('a\u0301haB')'Baha\u0301' // combining
3strrev('A\uD87E\uDC04Z')'Z\uD87E\uDC04A' // surrogates

« More PHP strings functions