In this post I'm going to show you how to create a jQuery utility function for reversing strings. JavaScript strings can be actually considered as arrays of characters, so we'll turn a string into an array and we'll use the reverse()
function of the Array
object to reverse the newly created array. Finally, we'll use the join()
function to turn our array into a new string. The jQuery code is as follows:
(function($) { $.reverseString = function(str) { if(typeof str !== 'string') { throw new Error('reverseString accepts only strings.'); return; } var strArr = str.split(''); var reversed = strArr.reverse(); return reversed.join(''); }; })(jQuery);
Note that we've also added a type check in order to know if the parameter passed to our utility function is actually a string. A simple test:
$(document).ready(function() { $('#run').click(function(e) { var str = $('#test').text(); var rev = $.reverseString(str); $('#test').text(rev); e.preventDefault(); }); });
You can see a demo below.