Search code examples
javascriptacrobatuppercase

Javascript - How to join two capitalize first letter of word scripts


I have an Acrobat form with some text fields with multiline on. My goal is to convert to uppercase the first letter of any sentence (look for dots) and also the first letter of any new line (after return has been pressed).

I can run each transformation separately, but do not know how to run them together.

To capitalize sentences I use the following code as custom convalidation :

// make an array split at dot
var aInput = event.value.split(". ");
var sCharacter = '';
var sWord='';

// for each element of word array, capitalize the first letter
for(i = 0; i <aInput.length; i++) 
{
  aInput[i] = aInput[i].substr(0, 1).toUpperCase() + aInput[i].substr(1) .toLowerCase();
}

// rebuild input string with modified words with dots
event.value = aInput.join('. ');

To capitalize new lines I replace ". " with "\r".

Thanks in advance for any help.


Solution

  • You can get the first character of each sentence with RegExp :

    event.value = event.value.replace(/.+?[\.\?\!](\s|$)/g, function (txt) {
        return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    });
    

    Demo : http://jsfiddle.net/00kzc370/

    Regular Expression explained :

    • /.+?[\.\?\!](\s|$)/g is a regular expression.
    • .+?[\.\?\!](\s|$) is a pattern (to be used in a search) that match sentences ended by ., ? or ! and followed by a whitespace character.
    • g is a modifier. (Perform a global match (find all matches rather than stopping after the first match)).

    Source : http://www.w3schools.com/jsref/jsref_obj_regexp.asp