Here is the function to convert string to title case, which can handle spaces and underscores. Below function will remove underscores from the string.
// Import the function function convertToTitleCase(input) { return input.toLowerCase().replace(/_/g, ' ').replace(/\b\w/g, function(match) { return match.toUpperCase(); }); }
You can call the convertToTitleCase
function in HTML by including a script tag with the function definition, and then using JavaScript to call the function and display the result.
Here's an example of how you can call the convertToTitleCase
function in HTML:
<!DOCTYPE html> <html> <head> <title>Convert to Title Case</title> </head> <body> <p id="output"></p> <script> // Function definition function convertToTitleCase(input) { return input.toLowerCase().replace(/_/g, ' ').replace(/\b\w/g, function(match) { return match.toUpperCase(); }); } // Call the function and display the result let input = "Nagasai_Srinivas_Mudara"; let convertedString = convertToTitleCase(input); document.getElementById("output").innerHTML = convertedString; </script> </body> </html>
In this JavaScript function, the replace
method is used with a regular expression to match the underscores and lowercase letters and convert the lowercase letters to uppercase when preceded by an underscore or at the beginning of the string.
You can use the convertToTitleCase
function to convert any input string to title case in a generic and reusable way.
No comments:
Post a Comment