How to capitalise the first letter of every word i

2019-09-08 15:44发布

I am using the Flex SDK and able to capitalise the first letter of every word as follows:

textInput.text.toLowerCase().replace(/\b./g,function(...m):String{return m[0].toUpperCase()})

This works fine, however letters after punctuation are also being capitalised, which works in some cases (e.g. O'Neil) but not others (e.g. Connah'S Quay).

I want to have the code only look at letters at the start of a string and letters after a space. Can anyone provide the correct code to use in this instance please?

5条回答
【Aperson】
2楼-- · 2019-09-08 15:56
  var input = "i aM tHe kiNG";
  capitalised = capitalize(input);
  function capitalize(input)
  {
    var splited = input.split(" ");
    //console.log(splited);
    var output = Array();
    for (i in splited)
    {
      //convert each letter into lower case
      var temp = splited[i].toLowerCase();
      //Convert the first char upper case and join with the rest letters of word.
      temp = temp.charAt(0).toUpperCase() + temp.substring(1);
      //store the word in the array
      output.push(temp);
    }
    //join the words
    return output.join(" ");
  }

The output will be: I Am The King

查看更多
Viruses.
3楼-- · 2019-09-08 16:01
private function capitalise(s:String):String
{
    var strArray:Array = s.split(' ');
    var newArray:Array = new Array();
    for each (var str:String in strArray)
        newArray.push(str.charAt(0).toUpperCase()+str.slice(1));

    return newArray.join(' ');
}

trace(capitalise("this is a test - o'Neil - connah's quay"));

// Output: This Is A Test - O'Neil - Connah's Quay
查看更多
祖国的老花朵
4楼-- · 2019-09-08 16:05

If you prefer, try this regex:

/(^| )./g
查看更多
虎瘦雄心在
5楼-- · 2019-09-08 16:09

This snippet might help:

function firstLetterUpperCase(strData:String):String 
{
    var strArray:Array = strData.split(' ');
    var newArray:Array = [];
    for (var str:String in strArray) 
    {
       newArray.push(strArray[str].charAt(0).toUpperCase() + strArray[str].slice(1));
    }
    return newArray.join(' ');
}

//testing
var strs = "Testing cases (e.g. o'Neil) and others (e.g. connah's quay)."
trace(firstLetterUpperCase(strs));

Result is:

//Testing Cases (e.g. O'Neil) And Others (e.g. Connah's Quay).
查看更多
ゆ 、 Hurt°
6楼-- · 2019-09-08 16:21
var test = "thIS is a test ansWER to stack OVERFlow";

function process(sentence) {
    var words = sentence.split(" ");
    var processed = '';

    for(var i=0; i < words.length; i++) {
        processed += words[i].substr(0,1).toUpperCase() +
        words[i].substr(1).toLowerCase();

        if(i < words.length-1) {
            processed += " ";
        }
    }
    return processed;
}

console.log(process(test));
查看更多
登录 后发表回答