EXERCISE · AlgoCasts
Reverse string
Given a string, return a new string with the reversed order of characters
Directions
Directions
Given a string, return a new string with the reversed order of characters
Examples#
JS
reverse('apple') === 'leppa'reverse('hello') === 'olleh'reverse('Greetings!') === '!sgniteerG'Try it first#
Copy the stub, make the 3 tests pass on your machine, then open the solution. The reveal is remembered per page in this browser.
JSexercises/reversestring/index.js
function reverse(str) {} module.exports = reverse;Solution#
JScompleted_exercises/reversestring/index.js
// string = 'ruhtrA';const reverse = (str) => { return str.split('').reduce((rev, char) => char + rev, '');}// console.log(reverse(string));module.exports = reverse;function reverse(str) { return str .split('') .reverse() .join('');}function reverse(str) { let reversed = ''; for (let character of str) { reversed = character + reversed; } return reversed;}const reverse = require('./index'); test('Reverse function exists', () => { expect(reverse).toBeDefined();}); test('Reverse reverses a string', () => { expect(reverse('abcd')).toEqual('dcba');}); test('Reverse reverses a string', () => { expect(reverse(' abcd')).toEqual('dcba ');}); Verbatim from the repo at 30cf7634. Alternate tabs are the commented-out solutions with the leading // removed and nothing else changed. Run the tests locally with npx jest reversestring inside the fork.
See also