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:
Author by
Kasper
Updated on July 08, 2022Comments
-
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 almost 7 yearswill complain when string is empty or not long enough.
-
Giraldi over 5 yearsI don't think this checks for
null
. -
Jawand Singh about 5 years@RishiDua well as a dev, (by default) we have the responsibility to check for those conditions 🐱👤
-
Dani over 4 yearsnice package. Thanks for sharing
-
Nguyễn Văn Phong over 4 yearsWhile this may answer the question, you should add more note to explain in order to help the OP know the reason why.
-
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 almost 4 yearsExtension should return
return "${this[0].toUpperCase()}${this.substring(1).toLowerCase()}";
. If not it will capitalize correctly 'this' but not 'THIS'. -
Hannah Stark almost 4 yearsdon't you normally check if a value is valid before operating with it?
-
FluffyKitten almost 4 yearsCode-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 almost 4 yearsgood solution, but doesn't work with letters with diacritics
-
Ndimah almost 4 yearsit's normal because of the regex if you wish to do it adjust the regex to include those letters
-
Vikas Jangra almost 4 yearsWe 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 almost 4 yearsgotta 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 over 3 years
str.capitalize
is not defined. So you usestr.inCaps
-
Maciej over 3 yearsyou should add some checks if string is not null - eg:
if (this == null || this == "") return "";
-
Gustavo Rodrigues over 3 yearsThis 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 over 3 yearsJust what I was looking for. Thanks!
-
Dario Brux over 3 yearsGreat library!!
-
WillHaslett about 3 yearsLooks 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 about 3 years
Uncaught Error: RangeError (index): Index out of range: no indices are valid: 0
-
BIS Tech about 3 years
final helloWorld = 'hello world'.capitalizeFirstofEach;
-
BIS Tech about 3 years
Uncaught Error: RangeError (index): Index out of range: no indices are valid: 0
-
BIS Tech about 3 years
String data = allWordsCapitilize('THIS IS A TEST') ;
-
Tom about 3 yearsI can't find any reference to this. Can you provide source?
-
Jing Wey about 3 yearsSorry, its under a plugin, my bad. Use this : link . It has a lot of useful utilities
-
Iván Yoed almost 3 yearsHey! Thanks for the response. I'm curious, what would be the benefit of
characters
? -
Gerry almost 3 yearsI 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 almost 3 yearsYes this is correct answer if you want to handle different locales in the right way. +1
-
Ndimah over 2 yearsI 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).toLowerCase()}'; }, ).trim();
-
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 over 2 yearsI just use: someString = someString[0].toUpperCase() + someString.substring(1).toLowerCase();
-
benten over 2 yearsthe best solution
-
Peter Bruins about 2 yearsThat will capitalize the whole string, instead of the first character.