Convert string to title case with JavaScript

后端 未结 30 2878
夕颜
夕颜 2020-11-21 06:40

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 R

相关标签:
30条回答
  • 2020-11-21 07:35

    Here’s my function that converts to title case but also preserves defined acronyms as uppercase and minor words as lowercase:

    String.prototype.toTitleCase = function() {
      var i, j, str, lowers, uppers;
      str = this.replace(/([^\W_]+[^\s-]*) */g, function(txt) {
        return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
      });
    
      // Certain minor words should be left lowercase unless 
      // they are the first or last words in the string
      lowers = ['A', 'An', 'The', 'And', 'But', 'Or', 'For', 'Nor', 'As', 'At', 
      'By', 'For', 'From', 'In', 'Into', 'Near', 'Of', 'On', 'Onto', 'To', 'With'];
      for (i = 0, j = lowers.length; i < j; i++)
        str = str.replace(new RegExp('\\s' + lowers[i] + '\\s', 'g'), 
          function(txt) {
            return txt.toLowerCase();
          });
    
      // Certain words such as initialisms or acronyms should be left uppercase
      uppers = ['Id', 'Tv'];
      for (i = 0, j = uppers.length; i < j; i++)
        str = str.replace(new RegExp('\\b' + uppers[i] + '\\b', 'g'), 
          uppers[i].toUpperCase());
    
      return str;
    }
    

    For example:

    "TO LOGIN TO THIS SITE and watch tv, please enter a valid id:".toTitleCase();
    // Returns: "To Login to This Site and Watch TV, Please Enter a Valid ID:"
    
    0 讨论(0)
  • 2020-11-21 07:39

    Taking the "lewax00" solution I created this simple solution that force to "w" starting with space or "w" that initiate de word, but is not able to remove the extra intermediate spaces.

    "SOFÍA vergara".toLowerCase().replace(/\b(\s\w|^\w)/g, function (txt) { return txt.toUpperCase(); });

    The result is "Sofía Vergara".

    0 讨论(0)
  • 2020-11-21 07:40

    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>

    0 讨论(0)
  • 2020-11-21 07:40

    A slightly more elegant way, adapting Greg Dean's function:

    String.prototype.toProperCase = function () {
        return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
    };
    

    Call it like:

    "pascal".toProperCase();
    
    0 讨论(0)
  • 2020-11-21 07:40

    ES 6

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

    else

    str.split(' ').map(function (s) {
        return s.slice(0, 1).toUpperCase() + s.slice(1).toLowerCase();
    }).join(' ')
    
    0 讨论(0)
  • 2020-11-21 07:41

    Here's my version, IMO it's easy to understand and elegant too.

    var str = "foo bar baz"
    
    console.log(
    
    str.split(' ')
       .map(w => w[0].toUpperCase() + w.substr(1).toLowerCase())
       .join(' ')
    
    )
    // returns "Foo Bar Baz"

    0 讨论(0)
提交回复
热议问题