I'm tyring to use a script to undo ALL CAPS in my text area

混江龙づ霸主 提交于 2019-12-11 20:29:46

问题


I have a textarea that receives inputs in ALL CAPS, which is fine for most users. Some users need the text represented in a normalized fasion - with the first letter of each sentence capitalized and the rest lowercase.

I tried to adapt some suggestions from other SO threads, but somethings is missing. Help please!

Body

<form>
        <input value="Select all" onclick="javascript:this.form.finaltext.focus();this.form.finaltext.select();"  type="button">
        <input value="Clear All" onclick="this.form.finaltext.value=''" type="button">
        <input value="Normalize text" type="button"  id="normalize">
        <a href="#" id="copy-textarea"><input type=button value="Copy to Clipboard"></a><br>
        <br>
        <textarea id="finaltext" cols="80" rows="50"> </textarea>
        </form>

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);
});
});

UPDATE 1 Now the script works.

NEW QUESTION How can I manipulate the logic in the .replace brackets for the following situation:

The text area I want to allow "normalization" is in the following format:

  • TEXT1
  • TEXT2
  • TEXT3

with a dash, space and ALL CAPS text. The .replace logic seems to only look for the first character in the string, but I would like it to treat each line (starting with the dash) separately and only leave the first letter thereafter capitalized.


回答1:


I'm taking the suggestion below and posting the corrected code that solved my click problem - credit to Ross:

I needed to wrap my script in a window.load function to include the function in the DOM after rendering.

$(window).load(function(){
...script...

}));


来源:https://stackoverflow.com/questions/17658473/im-tyring-to-use-a-script-to-undo-all-caps-in-my-text-area

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!