I've been trying to convert a string to title case using JavaScript. I have a snippet of code, but I'm facing some issues.

Example:



<script>
function toTitleCase(str) {
return str.replace(/\w\S*/g, function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}

let inputString = "this is a test string";
let titleCaseString = toTitleCase(inputString);
console.log(titleCaseString);
</script>

This code attempts to convert each word in a string to title case. However, I'm encountering a problem with words like "I" and "JavaScript", which should remain in uppercase. Can someone help me modify this code to handle such cases?