Henrik Petterson Henrik Petterson - 7 months ago 8
Javascript Question

Content of div should always start with capital letter and end with a full stop

I want to allow the user to remove words in a div tag, I do this simply by wrapping all words into

<span>
tags and target the tag, see awesome jsFiddle.

So the sentence inside the div is:


Hello world! 進撃の巨人 What isn't reality?


My question is, how can I make the sentence always start with a capital letter and end with a full stop, unless if the sentence ends with any of these characters:
.?!'")


So if user removes a few words and sentence is:


world! 進撃の巨人 What isn't


Then I want it to transform to:


World! 進撃の巨人 What isn't.

Answer

Try this updated fiddle

var endChars = [".", "?", "!", "\"", "'"];

jQuery(document).ready(function() {
    jQuery('.editable span').bind("mousedown", function() {

       jQuery(this).fadeOut(function(){
          var parentObj = $(this).parent();
          $(this).remove();
          var text = parentObj.find("span").first().html();
          console.log(text);
          parentObj.find("span").first().html(capitalizeFirstLetter(text)); 
          text = parentObj.find("span").last().html();
          if ( endChars.indexOf(text.slice(-1))  == -1 )
          {
            console.log(text);
            parentObj.find("span").last().html(text+"."); 
          }
       });

    });
});

function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}
Comments