Javascript - Adjusting string to title case logic
letterToCapitalize
finds the first occurrence of [a-zA-Z0-9_]
in each word you're trying to capitalize (the first suitable letter of).
In your code, you must remember that .replace(...)
actually returns a brand new string. It does not modify the string in place (in JavaScript, primitive data-types, of which strings are one, are not modifiable). The problem was you weren't assigning this new string to a variable that you were logging out.
let title = "Adjusting the title (case and test) on tv"
let titleCase = title.toLowerCase().split(' ').map((s) => {
let letterToCapitalize = s.match(/\w/)[0];
return s.replace(letterToCapitalize, letterToCapitalize.toUpperCase())
}).join(' ');
titleCase = titleCase.replace(/and/ig, '&').replace("Tv", "TV");
console.log(titleCase)
Convert string to title case with exceptions for articles (a, an, the..etc)
The Array.includes(String) function returns if the string is a part of the array.
This should work,
for(i = 0; i < splitStr.length; i++) {
// Check if our word is a part of the exceptions list
if(i>0 && exceptions.includes(splitStr[i]))
// if it's an exception skip the capatilization
continue;
splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1);
}
Credit for i>0 condition goes to @Ringo, i didn't think about that before. He's right that first word should always be capitalized regardless.
Converting snake case string to title case
Another plain regex version:
const titleCase = (s) =>
s.replace(/^_*(.)|_+(.)/g, (s, c, d) => c ? c.toUpperCase() : ' ' + d.toUpperCase())
console .log (titleCase ('big_animal'))
console .log (titleCase ('_big_animal___with_more_Nodes'))
Convert camelCaseText to Title Case Text
const text = 'helloThereMister';
const result = text.replace(/([A-Z])/g, " $1");
const finalResult = result.charAt(0).toUpperCase() + result.slice(1);
console.log(finalResult);
JavaScript titleCase function without regex
You will need to do an assignment for your string, so the first capital letter then the rest of the string as a lowercase:
strAr[i] = strAr[i].charAt(0).toUpperCase() + strAr[i].substring(1).toLowerCase();
Note the value strAr[i].charAt(0).toUpperCase()
will only return the first character as a capital letter, it will not actually change the string in any way.
Here is a simple example
Convert string to title case after dash or slash
Just change your capture of whitespace \s
, to be a class of characters being whitespace, a hyphen or a slash [\s-/]
(and anything else you want)
function toTitleCase(str) {
return str.toLowerCase().replace(/(?:^|[\s-/])\w/g, function (match) {
return match.toUpperCase();
});
}
console.log(toTitleCase("test here"));
console.log(toTitleCase("test/here"));
console.log(toTitleCase("test-here"));
Convert string to sentence case in javascript
Try this, It will work fine for you. It will also work for String having leading spaces.
var string="hi all, this is derp. thank you all to answer my query.";
var n=string.split(".");
var vfinal=""
for(i=0;i<n.length;i++)
{
var spaceput=""
var spaceCount=n[i].replace(/^(\s*).*$/,"$1").length;
n[i]=n[i].replace(/^\s+/,"");
var newstring=n[i].charAt(n[i]).toUpperCase() + n[i].slice(1);
for(j=0;j<spaceCount;j++)
spaceput=spaceput+" ";
vfinal=vfinal+spaceput+newstring+".";
}
vfinal=vfinal.substring(0, vfinal.length - 1);
alert(vfinal);
Javascript - Convert string title-case with hyphen in title
let secondTitle = "Retail sales - online order";
let secondCase = secondTitle.toLowerCase().replace(/\b[a-z]/g, function (s) {
return s.toUpperCase();
});
console.log(secondCase);
Most efficient way to turn all caps into title case with JS or JQuery?
You could match consecutive word characters, and use a replacer function to replace with the first character (as-is), followed by the rest with toLowerCase()
called on them:
const text = 'THIS IS MY STRING WHY AM I YELLLING?';
const output = text.replace(
/(\w)(\w*)/g,
(_, firstChar, rest) => firstChar + rest.toLowerCase()
);
console.log(output);
Related Topics
How to Test For an Empty JavaScript Object
How to Insert an Item into an Array At a Specific Index (JavaScript)
Group Array Items Using Object
Remove Accents/Diacritics in a String in JavaScript
Do You Recommend Using Semicolons After Every Statement in JavaScript
How May I Reference the Script Tag That Loaded the Currently-Executing Script
Convert String to Title Case With JavaScript
Difference Between Call and Apply
How to Get the Caret Column (Not Pixels) Position in a Textarea, in Characters, from the Start
How to Get the Current Date in JavaScript
Disable/Enable an Input With Jquery
What Is Spreadelement in Ecmascript Documentation? Is It the Same as Spread Syntax At Mdn
How to Do Case Insensitive String Comparison