1

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 Answers1

1

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.

Shiv
  • 370
  • 1
  • 14
  • Why StackOverflow Bot suggested it as the wrong question? It completely missed the reverse word. It refers https://stackoverflow.com/questions/32589197/how-can-i-capitalize-the-first-letter-of-each-word-in-a-string-using-javascript – Arka Bhattacharjee Apr 27 '22 at 23:28
  • 1
    @ArkaBhattacharjee Your code to reverse the string works. Simply capitalize each letter first, then reverse. – Spectric Apr 27 '22 at 23:30
  • is there any other way to avoid regex and limited it inside string only? – Arka Bhattacharjee Apr 27 '22 at 23:30
  • 1
    @ArkaBhattacharjee Try `ar.split(' ').map(e => [...(e[0].toUpperCase() + e.substr(1))].reverse().join('')).reverse().join(' ')`, which uses an array-only approach – Spectric Apr 27 '22 at 23:34