I'm trying to adapt a script that converts ALL CAPS text in a text area to lowercase (with the first word capitalized). Part of my issue was resolved here.
It works, but... my textarea text is in the following format: dash, space, then TEXT.
- TEXT1
- TEXT2
- TEXT3
The script I have , and the .replace logic, do not account for the "-" and space, and it does not account for each line separately.
here is the script:
$(window).load(function(){
$('#normalize').click(function capitalizeSentences(){
var capText = $("#finaltext").val();
capText = capText.toLowerCase();
capText = capText.replace(/\.\n/g,". [-<br>-]. ");
capText = capText.replace(/\.\s\n/g,". [-<br>-]. ");
var wordSplit = '. ';
var wordArray = capText.split(wordSplit);
var numWords = wordArray.length;
for(x=0;x<numWords;x++) {
wordArray[x] = wordArray[x].replace(wordArray[x].charAt(0),wordArray[x].charAt(0).toUpperCase());
if(x==0) {
capText = wordArray[x]+". ";
}else if(x != numWords -1){
capText = capText+wordArray[x]+". ";
}else if(x == numWords -1){
capText = capText+wordArray[x];
}
}
capText = capText.replace(/\[-<br>-\]\.\s/g,"\n");
capText = capText.replace(/\si\s/g," I ");
$("#finaltext").val(capText);
});
});
I don't follow the syntax or logic in the .replace() portions. Is there a primer on how the logic is constructed, or can someone give me a breakdown so I can adapt it more precisely?
Okay, after some reading on RegEx and some trial and error, I have (stumbled) upon the solution to my problem.
I realized that most of the stuff in the script I adapted was irrelevant junk. So I stepped back and took the problem piecemeal.
First, I decided to render all the text in lowercase:
var capText = $('#finaltext').val();
capText=capText.toLowerCase();
then, I needed to use .replace to find all instances of "dash+space+any letter":
.replace(/- ./g,
This will find the one letter after the dash in all instances, then I combine with a function to make uppercase:
.replace(/- ./g, function(c){return c.toUpperCase();});
final code is:
$('#normalize').click(function capitalizeSentences() {
var capText = $('#finaltext').val();
capText=capText.toLowerCase();
capText2 = capText.replace(/- ./g,function(c){ return c.toUpperCase(); });
$("#finaltext").val(capText2);
});
See here - http://jsfiddle.net/fDy6K/