Apu
January 19, 2024 .
#HowTo
.
#Javascript
❌
Convert string to title case with javascript example
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?
save
listen
AI Answer
Convert string to title case with javascript example
3
I've been trying to convert a string to title case using JavaScript. I have a snippet…
asked
Apu
3 answers
2915
I've been trying to convert a string to title case using JavaScript. I have a snippet…
Answer Link
answered
Apu
https://www.3schools.in/p/embed.html?q=CjxzY3JpcHQ+CiBmdW5jdGlvbiB0b1RpdGxlQ2FzZShzdHIpIHsKICBjb25zdCBleGNlcHRpb25zID0gWyJJIiwgIkphdmFTY3JpcHQiXTsKICByZXR1cm4gc3RyLnJlcGxhY2UoL1x3XFMqL2csIGZ1bmN0aW9uKHR4dCkgewogICAgaWYgKGV4Y2VwdGlvbnMuaW5jbHVkZXModHh0KSkgewogICAgICByZXR1cm4gdHh0OwogICAgfSBlbHNlIHsKICAgICAgcmV0dXJuIHR4dC5jaGFyQXQoMCkudG9VcHBlckNhc2UoKSArIHR4dC5zdWJzdHIoMSkudG9Mb3dlckNhc2UoKTsKICAgIH0KICB9KTsKfQoKbGV0IGlucHV0U3RyaW5nID0gInRoaXMgaXMgYSB0ZXN0IHN0cmluZyBpbiBKYXZhU2NyaXB0IjsKbGV0IHRpdGxlQ2FzZVN0cmluZyA9IHRvVGl0bGVDYXNlKGlucHV0U3RyaW5nKTsKY29uc29sZS5sb2codGl0bGVDYXNlU3RyaW5nKTsKPC9zY3JpcHQ+
Now, words in the "exceptions" array won't be converted to title case.
This code uses a word boundary ("\b") to match whole words and handles acronyms like "HTML" and "…