在字符串中大写单词的最佳方法是什么?


当前回答

使用JavaScript和html

String.prototype.capitalize = function() { 返回this.replace (/ (^ | \ s) ([a - z]) / g函数(m, p1, p2) { return p1 + p2.toUpperCase(); }); }; <form name="form1" method="post"> <input name="instring" type="text" value="this is the text string" size="30"> <input type="button" name="Capitalize" value="Capitalize >>" onclick="form1.outstring.value=form1.instring.value.capitalize();" > <input name="outstring" type="text" value="" size="30"> > < /形式

基本上,你可以用string。capitalize()它会大写每个单词的第一个字母。

来源:http://www.mediacollege.com/internet/javascript/text/case-capitalize.html

其他回答

function capitalize(s){
    return s.toLowerCase().replace( /\b./g, function(a){ return a.toUpperCase(); } );
};

capitalize('this IS THE wOrst string eVeR');

输出:“这是有史以来最糟糕的字符串”

更新:

这个解决方案似乎取代了我的:https://stackoverflow.com/a/7592235/104380

还有loctus: https://locutus.io/php/strings/ucwords/,它是这样定义的:

function ucwords(str) {
  //  discuss at: http://locutus.io/php/ucwords/
  // original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
  // improved by: Waldo Malqui Silva (http://waldo.malqui.info)
  // improved by: Robin
  // improved by: Kevin van Zonneveld (http://kvz.io)
  // bugfixed by: Onno Marsman (https://twitter.com/onnomarsman)
  // bugfixed by: Cetvertacov Alexandr (https://github.com/cetver)
  //    input by: James (http://www.james-bell.co.uk/)
  //   example 1: ucwords('kevin van  zonneveld')
  //   returns 1: 'Kevin Van  Zonneveld'
  //   example 2: ucwords('HELLO WORLD')
  //   returns 2: 'HELLO WORLD'
  //   example 3: ucwords('у мэри был маленький ягненок и она его очень любила')
  //   returns 3: 'У Мэри Был Маленький Ягненок И Она Его Очень Любила'
  //   example 4: ucwords('τάχιστη αλώπηξ βαφής ψημένη γη, δρασκελίζει υπέρ νωθρού κυνός')
  //   returns 4: 'Τάχιστη Αλώπηξ Βαφής Ψημένη Γη, Δρασκελίζει Υπέρ Νωθρού Κυνός'

  return (str + '').replace(/^(.)|\s+(.)/g, function ($1) {
    return $1.toUpperCase();
  });
};

我喜欢简单的过程。首先将字符串更改为数组,以便于迭代,然后使用map函数更改每个单词,因为你想要它是。

function capitalizeCase(str) {
    var arr = str.split(' ');
    var t;
    var newt;
    var newarr = arr.map(function(d){
        t = d.split('');
        newt = t.map(function(d, i){
                  if(i === 0) {
                     return d.toUpperCase();
                    }
                 return d.toLowerCase();
               });
        return newt.join('');
      });
    var s = newarr.join(' ');
    return s;
  }

一个简单,直接(非正则)的解决方案:

const capitalizeFirstLetter = s => 
  s.split(' ').map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(' ')

将字符串拆分为单词数组(使用空格分隔符) 将每个单词分成第一个字符+单词中的其余字符 第一个字母转换为大写字母,其余字母保持原样 将数组连接回带有空格的字符串

Ivo的答案很好,但我更喜欢不匹配\w,因为没有必要大写0-9和A-Z。我们可以忽略这些,只匹配a-z。

'your string'.replace(/\b[a-z]/g, match => match.toUpperCase())
// => 'Your String'

这是相同的输出,但我认为在自文档代码方面更清楚。