javascript – REGEX – Capitalized words in the middle of the sentence

Question:

Is there any regex/replace to make middle-sentence uppercase words to lowercase?

(Yes, I could pass everything to Lower) but there is a catch in this, the rule should be ignored if the word is after the period (.).

Example:

  • Unauthenticated User. Contact the ADM.

for:

  • User not authenticated. Contact the ADM.

Answer:

You can use this regex:

/^[^]([^.]*)/

It captures the text from the beginning to the last character before the first . , ignoring the first character ( [^] ) storing in group 1. Then you convert it to lowercase with .toLowerCase() in replace :

 var string = "UsuÁrio Não AUtenticadO. Contate o ADM."; var res = string.match(/^[^]([^.]*)/)[1]; string = string.replace(res,res.toLowerCase()); console.log(string);

Or you can take everything down to the word "Contact":

/[^](.+?(?=.\sContate))/
 var string = "UsuÁrio Não AUtenticadO. Contate o ADM."; var res = string.match(/[^](.*?(?=.\sContate))/)[1]; string = string.replace(res,res.toLowerCase()); console.log(string);

EDIT

If there are dots in the middle of the string, this regex ignores the first capital letter after the dot. As the result returns an array with more than 1 match , it was necessary to loop the array ignoring the last match ( Contate o ADM ):

/([^.\sA-Z][^.]*)/g
 var string = "Usuário Não Autenticado. Contate o ADM. Em Caso De Ou O A. Vou À Bahia. UsuÁrio Não AUtenTicadO. Ok Vamos testa. Contate o ADM."; var regex = /([^.\sA-Z][^.]*)/g var res = string.match(regex); for(let x=0; x<res.length-1; x++){ string = string.replace(res[x],res[x].toLowerCase()); } console.log(string);
Scroll to Top