DEV Community 👩‍💻👨‍💻


Posted on

Reverse Only Letters

Given a string s, reverse the string according to the following rules:

All the characters that are not English letters remain in the same position.
All the English letters (lowercase or uppercase) should be reversed.
Return s after reversing it.

Example 1:

Input: s = "ab-cd"
Output: "dc-ba"
Example 2:

Input: s = "a-bC-dEf-ghIj"
Output: "j-Ih-gfE-dCba"
Example 3:

Input: s = "Test1ng-Leet=code-Q!"
Output: "Qedo1ct-eeLg=ntse-T!"

var reverseOnlyLetters = function (arr) {
  let str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  let start = 0;
  let end = arr.length - 1;
  let s = arr.split("");

  while (start < end) {
    let charStart = s[start];
    let charEnd = s[end];

    if (str.includes(charStart) && str.includes(charEnd)) {
      s = swapChars(s, start, end);

    if (!str.includes(charStart)) {
    if (!str.includes(charEnd)) {
  return s.join("");

const swapChars = (s, start, end) => {
  let firstChar = s[start];
  let enChar = s[end];
  s[start] = enChar;
  s[end] = firstChar;
  return s;

// Output: "dc-ba"

// Output: "j-Ih-gfE-dCba"

// Output: "Qedo1ct-eeLg=ntse-T!"

Enter fullscreen mode Exit fullscreen mode

Top comments (0)

This post blew up on DEV in 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!