Santhosh Kumar Santhosh Kumar - 1 year ago 116
Javascript Question

Regex to select and replace as title case value

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
<button id="result">

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download