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".
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();
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'
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'));
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
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:
Super late, but I use,
String title = "some string with no first letter caps";
title = title.replaceFirst(title[0], title[0].toUpperCase()); // Some string with no...
You can use this package in flutter ReCase It gives you various case conversion functionalities like:
CONSTANT_CASE
ReCase sample = new ReCase('hello world');
print(sample.sentenceCase); // Prints 'Hello world'
void allWordsCapitilize (String str) {
return str.toLowerCase().split(' ').map((word) {
String leftText = (word.length > 1) ? word.substring(1, word.length) : '';
return word[0].toUpperCase() + leftText;
}).join(' ');
}
allWordsCapitilize('THIS IS A TEST'); //This Is A Test
As mentioned before by Ephenodrom, you can add basic_utils package in your pubspeck.yaml and use it in your dart files like this:
StringUtils.capitalize("yourString");
That's acceptable for a single function, but in a larger chain of operations, it becomes awkward.
As explained in Dart language documentation:
doMyOtherStuff(doMyStuff(something.doStuff()).doOtherStuff())
That code is much less readable than:
something.doStuff().doMyStuff().doOtherStuff().doMyOtherStuff()
The code is also much less discoverable because an IDE can suggest doMyStuff()
after something.doStuff()
, but will be unlikely to suggest putting doMyOtherStuff(…)
around the expression.
For these reasons, I think you should add an extension method to String type (you can do it since dart 2.6!) like this:
/// Capitalize the given string [s]
/// Example : hello => Hello, WORLD => World
extension Capitalized on String {
String capitalized() => this.substring(0, 1).toUpperCase() + this.substring(1).toLowerCase();
}
and call it using dot notation:
'yourString'.capitalized()
or, if your value can be null, replacing the dot with a '?.' in the invocation:
myObject.property?.toString()?.capitalized()
If you are using get: ^4.6.5 as state management with flutter then there are inbuilt extensions for capitalizing
// This will capitalize first letter of every word
print('hello world'.capitalize); // Hello World
// This will capitalize first letter of sentence
print('hello world'.capitalizeFirst); // Hello world
// This will remove all white spaces from sentence
print('hello world'.removeAllWhitespace); // helloworld
// This will convert string to lowerCamelCase
print('This is new world'.camelCase); // thisIsNewWorld
// This will remove all white spaces between the two words and replace it with '-'
print('This is new world'.paramCase); // this-is-new-world
String capitalize(String s) => (s != null && s.length > 1)
? s[0].toUpperCase() + s.substring(1)
: s != null ? s.toUpperCase() : null;
It passes tests:
test('null input', () {
expect(capitalize(null), null);
});
test('empty input', () {
expect(capitalize(''), '');
});
test('single char input', () {
expect(capitalize('a'), 'A');
});
test('crazy input', () {
expect(capitalize('?a!'), '?a!');
});
test('normal input', () {
expect(capitalize('take it easy bro!'), 'Take it easy bro!');
});
String? toCapitalize(String? input) {
if (input == null || input.isEmpty) return input;
return '${input[0].toUpperCase()}${input.substring(1).toLowerCase()}';
}
or Extension:
extension StringExtension on String {
String? toCapitalize() {
if (this == null || this.isEmpty) return this;
return '${this[0].toUpperCase()}${this.substring(1).toLowerCase()}';
}
}
To check for null and empty string cases, also using the short notations:
String capitalizeFirstLetter(String s) =>
(s?.isNotEmpty ?? false) ? '${s[0].toUpperCase()}${s.substring(1)}' : s;
you can you use capitalize() method of the strings librarie, it's now availabe in the 0.1.2 version, and make sure to add the dependencie in the pubspec.yaml:
dependencies:
strings: ^0.1.2
and import it into the dart file :
import 'package:strings/strings.dart';
and now you can use the method which has the following prototype:
String capitalize(String string)
Example :
print(capitalize("mark")); => Mark
You should also check if the string is null or empty.
String capitalize(String input) {
if (input == null) {
throw new ArgumentError("string: $input");
}
if (input.length == 0) {
return input;
}
return input[0].toUpperCase() + input.substring(1);
}
This is another alternative to capitalize Strings in dart with the use of the String class Method splitMapJoin
:
var str = 'this is a test';
str = str.splitMapJoin(RegExp(r'\w+'),onMatch: (m)=> '${m.group(0)}'.substring(0,1).toUpperCase() +'${m.group(0)}'.substring(1).toLowerCase() ,onNonMatch: (n)=> ' ');
print(str); // This Is A Test
Weird this is not available in dart to begin with. Below is an extension to capitalize a String
:
extension StringExtension on String {
String capitalized() {
if (this.isEmpty) return this;
return this[0].toUpperCase() + this.substring(1);
}
}
It checks that the String
is not empty to begin with, then it just capitalizes the first letter and adds the rest
Usage:
import "path/to/extension/string_extension_file_name.dart";
var capitalizedString = '${'alexander'.capitalized()} ${'hamilton, my name is'.capitalized()} ${'alexander'.capitalized()} ${'hamilton'.capitalized()}');
// Print result: "Alexander Hamilton, my name is Alexander Hamilton"
As described in the article Dart string manipulation done right (see Scenario 4), whenever you are dealing with user input you should use characters
rather than the index.
// import 'package:characters/characters.dart';
final sentence = 'e\u0301tienne is eating.'; // étienne is eating.
final firstCharacter = sentence.characters.first.toUpperCase();
final otherCharacters = sentence.characters.skip(1);
final capitalized = '$firstCharacter$otherCharacters';
print(capitalized); // Étienne is eating.
In this particular example it would still work even if you were using the index, but it's still a good idea to get into the habit of using characters
.
The characters package comes with Flutter so there is no need for the import. In a pure Dart project you need to add the import but you don't have to add anything to pubspec.yaml.
In range checked.
Idiomatic as of Dart >2.16.1
As a function
String capitalize(String str) =>
str.isNotEmpty
? str[0].toUpperCase() + str.substring(1)
: str;
As an extension
extension StringExtension on String {
String get capitalize =>
isNotEmpty
? this[0].toUpperCase() + substring(1)
: this;
}
var original = "this is a string";
var changed = original.substring(0, 1).toUpperCase() + original.substring(1);
This code works for me.
String name = 'amina';
print(${name[0].toUpperCase()}${name.substring(1).toLowerCase()});
The simplest answer is here:
First make the string's first letter to uppercase using its index then concate the rest of the string.
Here username is the string.
username[0].toUpperCase() + username.substring(1);
extension StringExtension on String {
String capitalize() {
return this
.toLowerCase()
.split(" ")
.map((word) => word[0].toUpperCase() + word.substring(1, word.length))
.join(" ");
}
}
For anyone interested, this should work on any string
You can use this function:
String capitalize(String str) {
return str
.split(' ')
.map((word) => word.substring(0, 1).toUpperCase() + word.substring(1))
.join(' ');
}
Some of the more popular other answers don't seem to handle null
and ''
. I prefer to not have to deal with those situations in client code, I just want a String
in return no matter what - even if that means an empty one in case of null
.
String upperCaseFirst(String s) => (s??'').length<1 ? '' : s[0].toUpperCase() + s.substring(1)
You can use the Text_Tools package, is simple to use:
https://pub.dev/packages/text_tools
Your code would be like this:
//This will print 'This is a string
print(TextTools.toUppercaseFirstLetter(text: 'this is a string'));
Another unhealthy way I found of solving this issue is to
String myName = "shahzad";
print(myName.substring(0,1).toUpperCase() + myName.substring(1));
this will produce the same effect but is pretty dirty way of doing it.
I've used Hannah Stark answer, but it crashes the app, if the string is empty, so here is improved version of the solution with the extension:
extension StringExtension on String {
String capitalize() {
if(this.length > 0) {
return "${this[0].toUpperCase()}${this.substring(1)}";
}
return "";
}
}
You can use this one:
extension EasyString on String {
String toCapitalCase() {
var lowerCased = this.toLowerCase();
return lowerCased[0].toUpperCase() + lowerCased.substring(1);
}
}
String fullNameString =
txtControllerName.value.text.trim().substring(0, 1).toUpperCase() +
txtControllerName.value.text.trim().substring(1).toLowerCase();
Herewith Sharing my answer
void main() {
var data = allWordsCapitilize(" hi ram good day");
print(data);
}
String allWordsCapitilize(String value) {
var result = value[0].toUpperCase();
for (int i = 1; i < value.length; i++) {
if (value[i - 1] == " ") {
result = result + value[i].toUpperCase();
} else {
result = result + value[i];
}
}
return result;
}
I used a different implementation:
import 'package:flutter/services.dart';
class FirstLetterTextFormatter extends TextInputFormatter {
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue, TextEditingValue newValue) {
return TextEditingValue(
//text: newValue.text?.toUpperCase(),
text: normaliseName(newValue.text),
selection: newValue.selection,
);
}
/// Fixes name cases; Capitalizes Each Word.
String normaliseName(String name) {
final stringBuffer = StringBuffer();
var capitalizeNext = true;
for (final letter in name.toLowerCase().codeUnits) {
// UTF-16: A-Z => 65-90, a-z => 97-122.
if (capitalizeNext && letter >= 97 && letter <= 122) {
stringBuffer.writeCharCode(letter - 32);
capitalizeNext = false;
} else {
// UTF-16: 32 == space, 46 == period
if (letter == 32 || letter == 46) capitalizeNext = true;
stringBuffer.writeCharCode(letter);
}
}
return stringBuffer.toString();
}
}
Then you import the class into any page you need eg in a TextField's inputFormatters property, just call the widget above like so:
TextField(
inputformatters: [FirstLetterTextFormatter()]),
),
Here is the code if you want to capitalize each word in a sentence, for example, if you want to capitalize each part of your customer's fullName, simply you can use the following extension in your model class:
extension StringExtension on String {
String capitalizeFirstLetter() {
return "${this[0].toUpperCase()}${this.substring(1).toLowerCase()}";
}
}
and simply use this getter
String get formalFullName => fullName.capitalizeFirstLetter().splitMapJoin(RegExp(r' '),
onNonMatch: (str) => str.toString().capitalize());
Hope this help someone
capitalize("your text");
simply wrap that text to capitalize widget and it makes your text (your text) to (Your text) .. have a great day
Text("hello world".capitalize.toString(), style: TextStyle(
fontSize: 25,
fontWeight: FontWeight.bold,
),
),
you can capitalize each word of a string by define the capitalize() method.
extension StringExtensions on String {
String capitalize() {
return '${this[0].toUpperCase()}${substring(1)}';
}
}
how to use?
String myString = 'capitalized_the_first_letter_of_every_word_the_string';
myString = myString.replaceAll('_', ' ');
String capitalizedString = myString.split(' ').map((word) => word.capitalize()).join(' ');
code example :
class CapitalizeText extends StatefulWidget {
const CapitalizeText({super.key});
@override
State<CapitalizeText> createState() => _CapitalizeTextState();
}
class _CapitalizeTextState extends State<CapitalizeText> {
@override
Widget build(BuildContext context) {
String myString = 'capitalized_the_first_letter_of_every_word_the_string';
myString = myString.replaceAll('_', ' ');
String capitalizedString = myString.split(' ').map((word) => word.capitalize()).join(' ');
return Scaffold(
body: Text(
'Capitalized String - $capitalizedString',
style: const TextStyle(fontWeight: FontWeight.w200, fontSize: 20),
),
);
}
}
extension StringExtensions on String {
String capitalize() {
return '${this[0].toUpperCase()}${substring(1)}';
}
}
Input: capitalized_the_first_letter_of_every_word_the_string
Output: Capitalized The First Letter Of Every Word The String
String myString = "hello world";
final capitalizedString = myString.replaceAll(RegExp(' +'), ' ').split(' ').map((capitalizedString) => capitalizedString.substring(0, 1).toUpperCase() +capitalizedString.substring(1)).join(' ');
void main(){
print(capitalizedString);
}
Another way.
import 'package:parser_combinator/parser/any.dart';
import 'package:parser_combinator/parser/choice.dart';
import 'package:parser_combinator/parser/join.dart';
import 'package:parser_combinator/parser/mapped.dart';
import 'package:parser_combinator/parser/rest.dart';
import 'package:parser_combinator/parser/sequence.dart';
import 'package:parser_combinator/parser/value.dart';
import 'package:parser_combinator/parsing.dart';
void main(List<String> args) {
print(capitalize('abc'));
print(capitalize(''));
print(capitalize('xyz'));
print(capitalize('Abc'));
}
String capitalize(String s) {
const p = Choice2(
Join('', Sequence2(Mapped(Any(), _capitalize), Rest())),
Value<String, String>(''),
);
return parseString(p.parse, s);
}
String _capitalize(String s) => s.toUpperCase();
This method is also quite fast.
import 'package:parser_combinator/parser/any.dart';
import 'package:parser_combinator/parser/choice.dart';
import 'package:parser_combinator/parser/join.dart';
import 'package:parser_combinator/parser/mapped.dart';
import 'package:parser_combinator/parser/rest.dart';
import 'package:parser_combinator/parser/sequence.dart';
import 'package:parser_combinator/parser/value.dart';
import 'package:parser_combinator/parsing.dart';
void main(List<String> args) {
const count = 1000000;
final sw = Stopwatch();
sw.start();
for (var i = 0; i < count; i++) {
'abc'.capitalize();
}
sw.stop();
print('Low level: ${sw.elapsedMilliseconds / 1000} sec');
sw.reset();
sw.start();
for (var i = 0; i < count; i++) {
capitalize('abc');
}
sw.stop();
print('High level: ${sw.elapsedMilliseconds / 1000} sec');
}
String capitalize(String s) {
const p = Choice2(
Join('', Sequence2(Mapped(Any(), _capitalize), Rest())),
Value<String, String>(''),
);
return parseString(p.parse, s);
}
String _capitalize(String s) => s.toUpperCase();
extension StringExtension on String {
String capitalize() {
return "${this[0].toUpperCase()}${this.substring(1).toLowerCase()}";
}
}
Output:
Low level: 0.084 sec
High level: 0.304 sec
If the Dart version is 2.12 or later, one of the simple and effective solutions to this problem would be,
extension Capitalizing on String {
String get capitalized {
if (isEmpty) return '';
return replaceFirst(this[0], this[0].toUpperCase());
}
}
Writing an extension
on String
class ensures code reusability and clean syntax, you can utilize the extension like this,
String yourString = 'this is a string';
final String capitalizedString = yourString.capitalized; //This is a string
As of 23/3/2021 Flutter 2.0.2
Just use yourtext.capitalizeFirst
if you are using it in flutter use as below,
For first letter of string to capitalize :
Text("hello world".toString().capitalizeFirstLetter()),
Convert all letter of string to capital
Text("hello world".toString().toUpperCase()),
Convert all letter of string to small
Text("hello world".toString().toLowerCase()),
Try this code to capitalize the first letter of any String in Dart - Flutter:
Example: hiii how are you
Code:
String str="hiii how are you";
Text( '${str[0].toUpperCase()}${str.substring(1)}',)`
Output: Hiii how are you
final helloWorld = 'hello world'.toUpperCase(); Text(helloWorld);