reverse in parentheses javascript

Reverse in parentheses JavaScript

If you want to reverse the characters inside a string, but keep the rest of the text intact, you can use JavaScript to do so. One way to accomplish this is to use the split(), reverse(), and join() methods.

Method 1: split(), reverse(), and join()


      let str = "Hello (world)";
      let parts = str.split("(");
      let lastPart = parts[parts.length - 1];
      let reversed = lastPart.split("").reverse().join("");
      let result = str.replace(lastPart, reversed);
      console.log(result); // "Hello (dlrow)"
    

This method works by first splitting the string at the open parenthesis using the split() method. This creates an array with two elements: the part before the parenthesis and the part inside the parenthesis. We then take the last element of that array (the part inside the parenthesis) and split it into an array of characters. We can then reverse that array using the reverse() method and join it back together into a string using the join() method. Finally, we replace the original part inside the parenthesis with the reversed string using the replace() method.

Method 2: Regular Expression

An alternative method that achieves the same result is to use a regular expression. This method uses a regular expression to match the text inside parentheses and then uses a function to reverse that text.


      let str = "Hello (world)";
      let result = str.replace(/\(([^)]+)\)/, function(match, contents) {
        return "(" + contents.split("").reverse().join("") + ")";
      });
      console.log(result); // "Hello (dlrow)"
    

This method uses the replace() method with a regular expression to match the text inside parentheses. The regular expression matches an open parenthesis followed by one or more characters that are not a close parenthesis, followed by a close parenthesis. The matched text (excluding the parentheses) is then passed to a function that reverses it using the same method as in the first example.

Both methods achieve the same result, so you can choose whichever one you find more readable or efficient for your specific use case.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe