I have this code where the input of first-name last-name will be converted to lowercase then the first letters of each word will be converted to uppercase and then swap place.
However, I ran into an inconvenience where special characters(not certain with the term) were not being processed.
Input: oNdřej rasZka Desired output: Raszka,Ondřej What I'm getting: OndŘEj Raszka
The "ŘE" of OndŘEj was not processed properly same with other available special characters, is there any way to solve this?
<div>
<textarea cols="50" rows="5" id="fullName" class= ""></textarea>
</div>
<button id="splitName">Click</button>
<div>
<br>
</div>
<div class= "border" id="result"></div>
var splitName = document.getElementById("splitName");
splitName.onclick = function() {
document.getElementById("result").innerHTML = '';
var value = document.getElementById("fullName").value;
//CASE CONVERT//
var value2 = value.toLowerCase();
value2 = value2.replace(/\b./g, function(m){ return m.toUpperCase(); });
value2.split('\n').forEach(fullname => {
var spaceIndex = fullname.indexOf(" ");
var firstname;
var lastname;
if (spaceIndex == -1) {
lastname = fullname;
lastname = "";
} else {
firstname = fullname.substring(0, spaceIndex);
lastname = fullname.substr(spaceIndex + 1);
}
document.getElementById("result").innerHTML += lastname + " " + firstname+ "<br>";
});
};
Thanks a lot.
You can slice off the first character, call toUpperCase on it and then concatenate it back onto the remainder of the string.
function capitalise(input) {
return `${input[0].toUpperCase()}${input.slice(1).toLowerCase()}`
}
This method avoids you converting everything to lower case and then having to switch the first character back. I suspect your regex is what's causing the issue, as it's likely reading characters that aren't there.
Alternatively, if you want to capitalise each name and you know the separating character you can do something like:
function capitalise(input, separator) {
const wordArray = input.split(separator);
const output = wordArray.map(word => `${word[0].toUpperCase()}${word.slice(1).toLowerCase()}`);
return output.join(separator);
}