开发者

Capitalize the first letter of every word

I want to use a javascript function to capitalize the first letter of every word

e开发者_高级运维g:

THIS IS A TEST ---> This Is A Test
this is a TEST ---> This Is A Test
this is a test ---> This Is A Test

What would be a simple javascript function


Here's a little one liner that I'm using to get the job done

var str = 'this is an example';
str.replace(/\b./g, function(m){ return m.toUpperCase(); });

but John Resig did a pretty awesome script that handles a lot of cases http://ejohn.org/blog/title-capitalization-in-javascript/

Update

ES6+ answer:

str.split(' ').map(s => s.charAt(0).toUpperCase() + s.slice(1)).join(' ');

There's probably an even better way than this. It will work on accented characters.


function capitalizeEachWord(str)
{
   var words = str.split(" ");
   var arr = [];
   for (i in words)
   {
      temp = words[i].toLowerCase();
      temp = temp.charAt(0).toUpperCase() + temp.substring(1);
      arr.push(temp);
   }
   return arr.join(" ");
}


"tHiS iS a tESt".replace(/[^\s]+/g, function(str){ 
    return str.substr(0,1).toUpperCase()+str.substr(1).toLowerCase();
  });

Other variant:

"tHiS iS a tESt".replace(/(\S)(\S*)/g, function($0,$1,$2){ 
    return $1.toUpperCase()+$2.toLowerCase();
  });


This is a simple solution that breaks down the sentence into an array, then loops through the array creating a new array with the capitalized words.

 function capitalize(str){

  var strArr = str.split(" ");
  var newArr = [];

  for(var i = 0 ; i < strArr.length ; i++ ){

    var FirstLetter = strArr[i].charAt(0).toUpperCase();
    var restOfWord = strArr[i].slice(1);

    newArr[i] = FirstLetter + restOfWord;

  }

  return newArr.join(' ');

}


take a look at ucwords from php.js - this seems to be kind of what you're looking for. basically, it's:

function ucwords (str) {
    return (str + '').replace(/^([a-z])|\s+([a-z])/g, function ($1) {
        return $1.toUpperCase();
    });
}

note that THIS IS A TEST will return THIS IS A TEST so you'll have to use it like this:

var oldstring = "THIS IS A TEST";
var newstring = ucwords(oldstring.toLowerCase());

or modify the function a bit:

function ucwords (str) {
    str = (str + '').toLowerCase();
    return str.replace(/^([a-z])|\s+([a-z])/g, function ($1) {
        return $1.toUpperCase();
    });
}
var oldstring = "THIS IS A TEST";
var newstring = ucwords(oldstring); // This Is A Test


This will capitalize every word seperated by a space or a dash

function capitalize(str){
    str = str.toLowerCase();
    return str.replace(/([^ -])([^ -]*)/gi,function(v,v1,v2){ return v1.toUpperCase()+v2; });
}

Examples :

  • i lOvE oRanges => I Love Oranges
  • a strAnge-looKing syntax => A Strange-Looking Syntax

etc


If you don't mind using a library, you could use Sugar.js capitalize()

capitalize( all = false ) Capitalizes the first character in the string and downcases all other letters. If all is true, all words in the string will be capitalized.

Example:

'hello kitty'.capitalize()     -> 'Hello kitty'
'hello kitty'.capitalize(true) -> 'Hello Kitty'


you can also use below approach using filter:

function Ucwords(str){
    var words = str.split(' ');
    var arr = [];
    words.filter(function(val){
        arr.push(val.charAt(0).toUpperCase()+ val.substr(1).toLowerCase());             
    })
    console.log(arr.join(" ").trim());
    return arr.join(" ").trim();
}

Ucwords("THIS IS A TEST") //This Is A Test

Ucwords("THIS ") //This


{
        String s = "this is for testing";
        String sw[] = s.split("\\s");
        String newS = "";
        for(int i=0; i<=sw.length-1; i++)
        {
            String first = sw[i].substring(0,1);
            String last = sw[i].substring(1);
            newS+= first.toUpperCase()+last+" ";
            
        }
        System.out.println(newS);
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜