Santhosh Kumar Santhosh Kumar - 12 days ago 6
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
</div>
<button id="result">
Result
</button>




Answer

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(...);
Comments