Convert string to title case with JavaScript

2018-12-31 01:48发布

Is there a simple way to convert a string to title case? E.g. john smith becomes John Smith. I'm not looking for something complicated like John Resig's solution, just (hopefully) some kind of one- or two-liner.

30条回答
不再属于我。
2楼-- · 2018-12-31 02:09

Try this:

    function toTitleCase(str) {
        return str.replace(
            /\w\S*/g,
            function(txt) {
                return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
            }
        );
    }
<form>
Input:
<br /><textarea name="input" onchange="form.output.value=toTitleCase(this.value)"  onkeyup="form.output.value=toTitleCase(this.value)"></textarea>
<br />Output:
<br /><textarea name="output" readonly onclick="select(this)"></textarea>
</form>

查看更多
姐姐魅力值爆表
3楼-- · 2018-12-31 02:09

This works only for one word strings but that's what I needed:

'string'.replace(/^[a-z]/, function (x) {return x.toUpperCase()}) // String

JSFiddle: https://jsfiddle.net/simo/gou2uhLm/

查看更多
君临天下
4楼-- · 2018-12-31 02:12
var toMatch = "john w. smith";
var result = toMatch.replace(/(\w)(\w*)/g, function (_, i, r) {
      return i.toUpperCase() + (r != null ? r : "");
    }
)

Seems to work... Tested with the above, "the quick-brown, fox? /jumps/ ^over^ the ¡lazy! dog..." and "C:/program files/some vendor/their 2nd application/a file1.txt".

If you want 2Nd instead of 2nd, you can change to /([a-z])(\w*)/g.

The first form can be simplified as:

function toTitleCase(toTransform) {
  return toTransform.replace(/\b([a-z])/g, function (_, initial) {
      return initial.toUpperCase();
  });
}
查看更多
琉璃瓶的回忆
5楼-- · 2018-12-31 02:12

My simple and easy version to the problem:

    function titlecase(str){
    var arr=[];  
    var str1=str.split(' ');
    for (var i = 0; i < str1.length; i++) {
    var upper= str1[i].charAt(0).toUpperCase()+ str1[i].substr(1);
    arr.push(upper);
     };
      return arr.join(' ');
    }
    titlecase('my name is suryatapa roy');
查看更多
梦该遗忘
6楼-- · 2018-12-31 02:12

It's not short but here is what I came up with on a recent assignment in school:

var myPoem = 'What is a jQuery but a misunderstood object?'
//What is a jQuery but a misunderstood object? --> What Is A JQuery But A Misunderstood Object?

  //code here
var capitalize = function(str) {
  var strArr = str.split(' ');
  var newArr = [];
  for (var i = 0; i < strArr.length; i++) {
    newArr.push(strArr[i].charAt(0).toUpperCase() + strArr[i].slice(1))
  };
  return newArr.join(' ')  
}

var fixedPoem = capitalize(myPoem);
alert(fixedPoem);

查看更多
无与为乐者.
7楼-- · 2018-12-31 02:14

You could immediately toLowerCase the string, and then just toUpperCase the first letter of each word. Becomes a very simple 1 liner:

function titleCase(str) {
  return str.toLowerCase().replace(/\b(\w)/g, s => s.toUpperCase());
}

console.log(titleCase('iron man'));
console.log(titleCase('iNcrEdible hulK'));

查看更多
登录 后发表回答