How to capitalize each words on starting of a string and after dot(.) sign?
I made a research on google and stackoverflow, below are the codes that I achieved but this will only capitalize starting of a string. Example as belows;
var str = 'this is a text. hello world!';
str = str.replace(/^(.)/g, str[0].toUpperCase());
document.write(str);
How to capitalize each words on starting of a string and after dot(.) sign?
I made a research on google and stackoverflow, below are the codes that I achieved but this will only capitalize starting of a string. Example as belows;
var str = 'this is a text. hello world!';
str = str.replace(/^(.)/g, str[0].toUpperCase());
document.write(str);
I want the string to be This is a text. Hello world!.
I have tried to use css, text-transform: capitalize;
but this will result in each word to be capitalize.
- Possible duplicate of Convert string to sentence case in javascript – Fiddles Commented Nov 18, 2016 at 4:15
- also see stackoverflow./q/37457557/405180 – Fiddles Commented Nov 18, 2016 at 4:17
2 Answers
Reset to default 5I use a function like this, that takes an optional second parameter that will convert the entire string to lowercase initially. The reason is that sometimes you have a series of Title Case Items. That You Wish
to turn into a series of Title case items. That you wish
to have as sentence case.
function sentenceCase(input, lowercaseBefore) {
input = ( input === undefined || input === null ) ? '' : input;
if (lowercaseBefore) { input = input.toLowerCase(); }
return input.toString().replace( /(^|\. *)([a-z])/g, function(match, separator, char) {
return separator + char.toUpperCase();
});
}
The regex works as follows
1st Capturing Group (^|\. *)
1st Alternative ^
^ asserts position at start of the string
2nd Alternative \. *
\. matches the character `.` literally (case sensitive)
* matches the character ` ` literally (case sensitive)
* Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
2nd Capturing Group ([a-z])
Match a single character present in the list below [a-z]
a-z a single character in the range between a (ASCII 97) and z (ASCII 122) (case sensitive)
You would implement it in your example like so:
var str = 'this is a text. hello world!';
str = sentenceCase(str);
document.write(str); // This is a text. Hello world!
Example jsfiddle
PS. in future, i find regex101 a hugely helpful tool for understanding and testing regex's
If you are using jquery, use this code
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
var str = "my name is Jhon. are you good. is it";
var str1 = str.split('.');
var str2 = "";
$.each(str1,function(i){
str2 += capitalize($.trim(str1[i]))+'. ';
});
console.log(str2);
catch the out put in str2
.
in my case its like the following.
My name is Jhon. Are you good. Is it.