JavaScript String Reverse and Capitalized

Viewed 91

I am looking for a simple solution to build Javascript a function through which I can reverse a word or a string.

I have gone through .split('').reverse().join('') solution from the community to reverse it correctly but now I am stuck on Capitalizing on Each First Character.

let ar = "looking for opportunities"
const a =(ar)=> {return ar.split('').reverse().join('')}

and then I am stuck. I need a solution that can serve both sentence and word.

Required Output : seitinutroppO roF gnikooL

1 Answers

Use regex.

let ar = "looking for opportunities"
ar = ar.replaceAll(/\w\S*/g,
    function(txt) {
      return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    }
)
const a =(ar)=> {return ar.split('').reverse().join('')}

This matches all characters after a space, then replaces it with an uppercase version.

Related