How to capitalize the first letter of a string in dart?

100,056

Solution 1

Since dart version 2.6, dart supports extensions:

extension StringExtension on String {
    String capitalize() {
      return "${this[0].toUpperCase()}${this.substring(1).toLowerCase()}";
    }
}

So you can just call your extension like this:

import "string_extension.dart";

var someCapitalizedString = "someString".capitalize();

Solution 2

Copy this somewhere:

extension StringCasingExtension on String {
  String toCapitalized() => length > 0 ?'${this[0].toUpperCase()}${substring(1).toLowerCase()}':'';
  String toTitleCase() => replaceAll(RegExp(' +'), ' ').split(' ').map((str) => str.toCapitalized()).join(' ');
}

Usage:

// import StringCasingExtension

final helloWorld = 'hello world'.toCapitalized(); // 'Hello world'
final helloWorld = 'hello world'.toUpperCase(); // 'HELLO WORLD'
final helloWorldCap = 'hello world'.toTitleCase(); // 'Hello World'

Solution 3

Substring parsing in the other answers do not account for locale variances. The toBeginningOfSentenceCase() function in the intl/intl.dart package handles basic sentence-casing and the dotted "i" in Turkish and Azeri.

import 'package:intl/intl.dart' show toBeginningOfSentenceCase;

print(toBeginningOfSentenceCase('this is a string'));

Solution 4

void main() {
  print(capitalize("this is a string"));
  // displays "This is a string"
}

String capitalize(String s) => s[0].toUpperCase() + s.substring(1);

See this snippet running on DartPad : https://dartpad.dartlang.org/c8ffb8995abe259e9643

Solution 5

There is a utils package that covers this function. It has some more nice methods for operation on strings.

Install it with :

dependencies:
  basic_utils: ^1.2.0

Usage :

String capitalized = StringUtils.capitalize("helloworld");

Github:

https://github.com/Ephenodrom/Dart-Basic-Utils

Share:
100,056
Kasper
Author by

Kasper

Updated on July 08, 2022

Comments

  • Kasper
    Kasper almost 2 years

    How do I capitalize the first character of a string, while not changing the case of any of the other letters?

    For example, "this is a string" should give "This is a string".

  • Rishi Dua
    Rishi Dua almost 7 years
    will complain when string is empty or not long enough.
  • Giraldi
    Giraldi over 5 years
    I don't think this checks for null.
  • Jawand Singh
    Jawand Singh about 5 years
    @RishiDua well as a dev, (by default) we have the responsibility to check for those conditions 🐱‍👤
  • Dani
    Dani over 4 years
    nice package. Thanks for sharing
  • Nguyễn Văn Phong
    Nguyễn Văn Phong over 4 years
    While this may answer the question, you should add more note to explain in order to help the OP know the reason why.
  • TomTom101
    TomTom101 over 4 years
    s[0].toUpperCase() + s.substring(1).toLowerCase(); in case the string is all upper case to start with.
  • Luciano Rodríguez
    Luciano Rodríguez almost 4 years
    Extension should return return "${this[0].toUpperCase()}${this.substring(1).toLowerCase()}"‌​;. If not it will capitalize correctly 'this' but not 'THIS'.
  • Hannah Stark
    Hannah Stark almost 4 years
    don't you normally check if a value is valid before operating with it?
  • FluffyKitten
    FluffyKitten almost 4 years
    Code-only answers are discouraged on Stack Overflow because they don't explain how it solves the problem. Please edit your answer to explain what the code does and how it answers the question, so that it is useful for other users also as well as the OP.
  • Palejandro
    Palejandro almost 4 years
    good solution, but doesn't work with letters with diacritics
  • Ndimah
    Ndimah almost 4 years
    it's normal because of the regex if you wish to do it adjust the regex to include those letters
  • Vikas Jangra
    Vikas Jangra almost 4 years
    We either have to check isEmpty inside capitalize() or leave it up to the caller. My preference is for the caller so the code doesn't need to get littered with .isEmpty() checks. You can add if (isEmpty) return this as the first line.
  • Lucas Chwe
    Lucas Chwe almost 4 years
    gotta check if this is empty to avoid the crash. i dont think toLowerCase() would crash with an empty string and neither should your extension
  • Ashan
    Ashan over 3 years
    str.capitalize is not defined. So you use str.inCaps
  • Maciej
    Maciej over 3 years
    you should add some checks if string is not null - eg: if (this == null || this == "") return "";
  • Gustavo Rodrigues
    Gustavo Rodrigues over 3 years
    This with addition to the extension method answer should be the answer. If you already use the intl package there is no reason to reinvent the wheel with the extension.
  • jwehrle
    jwehrle over 3 years
    Just what I was looking for. Thanks!
  • Dario Brux
    Dario Brux over 3 years
    Great library!!
  • WillHaslett
    WillHaslett about 3 years
    Looks great. Use with caution as there's only one test, however much you may dig the test case. String mockText = 'This is-Some_sampleText. YouDig?';
  • BIS Tech
    BIS Tech about 3 years
    Uncaught Error: RangeError (index): Index out of range: no indices are valid: 0
  • BIS Tech
    BIS Tech about 3 years
    final helloWorld = 'hello world'.capitalizeFirstofEach;
  • BIS Tech
    BIS Tech about 3 years
    Uncaught Error: RangeError (index): Index out of range: no indices are valid: 0
  • BIS Tech
    BIS Tech about 3 years
    String data = allWordsCapitilize('THIS IS A TEST') ;
  • Tom
    Tom about 3 years
    I can't find any reference to this. Can you provide source?
  • Jing Wey
    Jing Wey about 3 years
    Sorry, its under a plugin, my bad. Use this : link . It has a lot of useful utilities
  • Iván Yoed
    Iván Yoed almost 3 years
    Hey! Thanks for the response. I'm curious, what would be the benefit of characters?
  • Gerry
    Gerry almost 3 years
    I thought I liked Dart.... but this is quite special. Why wouldn't they have something like this in the core language? I wonder what else is missing!
  • user3056783
    user3056783 almost 3 years
    Yes this is correct answer if you want to handle different locales in the right way. +1
  • Ndimah
    Ndimah over 2 years
    I think a simpler Implementation is to handle the whitespace, not the words in the regex just change it with str = str.trim().splitMapJoin( RegExp(r'\s+'), onMatch: (m) => ' ', onNonMatch: (n) { return '${n.substring(0,1).toUpperCase()}${n.substring(1).toLowerCa‌​se()}'; }, ).trim();
  • tim-montague
    tim-montague over 2 years
    @GustavoRodrigues - Even if you are not currently using Intl this is a better answer, because this package is maintained by the Flutter / Dart team, while the extension method has to be maintained by the developer.
  • positrix
    positrix over 2 years
    I just use: someString = someString[0].toUpperCase() + someString.substring(1).toLowerCase();
  • benten
    benten over 2 years
    the best solution
  • Peter Bruins
    Peter Bruins about 2 years
    That will capitalize the whole string, instead of the first character.