I have a string like
FIRST SENTENCE. SECOND SENTENCE.
I want to lowercase the string in that way to capitalize the first letter of each sentence.
For example:
string = string.toLowerCase().capitalize();
only the first sentence is capitalized.
I have the
String.prototype.capitalize = function() { return this.charAt(0).toUpperCase() + this.slice(1); }
function
Does anyone know how to solve?
I have a string like
FIRST SENTENCE. SECOND SENTENCE.
I want to lowercase the string in that way to capitalize the first letter of each sentence.
For example:
string = string.toLowerCase().capitalize();
only the first sentence is capitalized.
I have the
String.prototype.capitalize = function() { return this.charAt(0).toUpperCase() + this.slice(1); }
function
Does anyone know how to solve?
Share Improve this question edited Feb 10, 2016 at 7:50 default locale 13.4k13 gold badges59 silver badges66 bronze badges asked Dec 7, 2013 at 13:25 zsola3075457zsola3075457 1774 silver badges14 bronze badges4 Answers
Reset to default 10If you only want to capitalize the first word of each sentence (not every word), then use this function:
function applySentenceCase(str) {
return str.replace(/.+?[\.\?\!](\s|$)/g, function (txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}
JSFiddle here
If you want to keep the formatting of the rest of the sentence and just capitalize the first letters, change txt.substr(1).toLowerCase()
to txt.substr(1)
Try this
function toTitleCase(str) {
return str.replace(/\w\S*/g, function (txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}
alert(toTitleCase('FIRST SENTENCE. SECOND SENTENCE.'))
DEMO
With Reference
This JS function will apply sentence case to the initial sentence and any sentences that follow a sentence that ends with . ? !
function applySentenceCase(str) {
var txt = str.split(/(.+?[\.\?\!](\s|$))/g);
for (i = 0; i < (txt.length-1); i++) {
if (txt[i].length>1){
txt[i]=txt[i].charAt(0).toUpperCase() + txt[i].substr(1).toLowerCase();
} else if (txt[i].length==1) {
txt[i]=txt[i].charAt(0).toUpperCase();
}
}
txt = txt.join('').replace(/\s\s/g,' ');
return txt;
}
alert(applySentenceCase("LOREM IPSUM DOLOR SIT AMET, CONSECTETUR ADIPISCING ELIT. sed congue hendrerit risus, ac viverra magna elementum in. InTeRdUm Et MaLeSuAdA fAmEs Ac AnTe IpSuM pRiMiS iN fAuCiBuS. phasellus EST purus, COMMODO vitae IMPERDIET eget, ORNARE quis ELIT."));
I think this will work for you
<a style="cursor:pointer;" onclick="capitaliseFirstLetter('hey wassup baby')">asd</a>
<div type="text" id="texts"></div>
Javascript
function capitaliseFirstLetter(string)
{
var array = string.split(" ");
for(i=0;i<array.length;i++){
var n = array[i];
var a = n.charAt(0).toUpperCase() + n.slice(1);
alert(a);
}
}
visit : http://jsfiddle/rVnFU/