0

I'm new to this regex part. My functionality is to replace every first character in a word as uppercase and remaining part in lowercase. I can easily loop through an change. But it might be costlier. To simplify it i'm trying Regex. I changed all the first character in a word to uppercase, But stuck on changing the remaining part to lowercase. How can i achieve. Refer the code below

var txt= document.getElementById('txt');
var result = document.getElementById('result');
result.onclick = titleCases;
function titleCases(){
       txt.innerText = txt.innerText.replace(/\b[a-z]/g,function(f){return f.toUpperCase();})
}
<div id="txt">
    replace The tExt
</div>
<button id="result">
  Result
</button>
Santhosh Kumar
  • 1,672
  • 1
  • 16
  • 26

1 Answers1

2

It's always a good idea to break a problem down as much as possible.

In this case, you want everything lowercase except the first letters, right?

So convert the whole thing to lowercase, then do your "first letter to uppercase" thing.

txt.innerText.toLowerCase().replace(...);
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • Works like a charm. Another question. How can i replace every 1st letter in a sentence in capital case. Ex **F**irst letter after special character must be. **C**apital – Santhosh Kumar Nov 21 '16 at 18:52
  • That's trickier, but probably something like `.replace(/(^|[\W\S]\s+)(\w)/g,function(_,prefix,letter) {return prefix+letter.toUpperCase();});` – Niet the Dark Absol Nov 21 '16 at 18:59
  • It doesn't work dude. See the bolded letters in my previous comment. Only that should be capitalized – Santhosh Kumar Nov 21 '16 at 19:07