Tuesday 18 August 2020

Reverse String in JavaScript

 The most "popular" way of reversing a string in JavaScript is the following code fragment, which is quite common:

function reverseString(str) {

 return str.split('').reverse().join('');

}

reverseString('string'); // "gnirts"

However, this will work only so long as the string being reversed does not contain surrogate pairs. Astral symbols,

Add caption


i.e. characters outside of the basic multilingual plane, may be represented by two code units, and will lead this

naive technique to produce wrong results. Moreover, characters with combining marks (e.g. diaeresis) will appear

on the logical "next" character instead of the original one it was combined with.

'?????.'.split('').reverse().join(''); //fails

While the method will work fine for most languages, a truly accurate, encoding respecting algorithm for string

reversal is slightly more involved. One such implementation is a tiny library called Esrever, which uses regular

expressions for matching combining marks and surrogate pairs in order to perform the reversing perfectly.

Explanation

Section Explanation Result

str The input string "string"

String.prototype.split(

deliminator )

Splits string str into an array. The

parameter "" means to split between each

character.

["s","t","r","i","n","g"]

Array.prototype.reverse()

Returns the array from the split string with

its elements in reverse order. ["g","n","i","r","t","s"]

Array.prototype.join( deliminator

)

Joins the elements in the array together into

a string. The "" parameter means an empty

deliminator (i.e., the elements of the array

are put right next to each other).


No comments:

Post a Comment