How to convert a string to uppercase in JavaScript
Converting strings to uppercase is essential for data normalization, case-insensitive comparisons, creating display headers, and implementing features like search matching or consistent text formatting in JavaScript applications.
With over 25 years of experience in software development and as the creator of CoreUI, I’ve implemented uppercase conversion extensively in components like form labels, button text, navigation headers, and search functionality where consistent capitalization enhances user experience and data processing.
From my extensive expertise, the most straightforward and universally supported solution is using the built-in toUpperCase() method.
This approach is simple, efficient, and specifically designed for case conversion with excellent browser compatibility.
Use the toUpperCase() method to convert all characters in a string to uppercase.
const text = 'hello world'
const uppercase = text.toUpperCase()
// Result: 'HELLO WORLD'
The toUpperCase() method converts all alphabetic characters in the string to their uppercase equivalents and returns a new string without modifying the original. In this example, 'hello world'.toUpperCase() transforms all lowercase letters to uppercase, resulting in 'HELLO WORLD'. Non-alphabetic characters like numbers, spaces, and punctuation remain unchanged. The method handles international characters correctly, converting accented letters and other Unicode characters to their proper uppercase forms.
1. Case-Insensitive String Comparison
Converting strings to the same case before comparing them is the standard approach for case-insensitive matching. While toLowerCase() is more common for this purpose, toUpperCase() works equally well.
const input = 'JavaScript'
const target = 'JAVASCRIPT'
// Direct comparison fails due to case difference
console.log(input === target)
// Result: false
// Normalize both to uppercase
console.log(input.toUpperCase() === target.toUpperCase())
// Result: true
// Case-insensitive array search
const roles = ['Admin', 'editor', 'VIEWER', 'moderator']
const userRole = 'admin'
const hasRole = roles.some(
role => role.toUpperCase() === userRole.toUpperCase()
)
// Result: true
// Case-insensitive object key lookup
const config = { 'Content-Type': 'application/json', 'Accept': 'text/html' }
const findHeader = (headers, name) => {
const upperName = name.toUpperCase()
return Object.entries(headers).find(
([key]) => key.toUpperCase() === upperName
)
}
console.log(findHeader(config, 'content-type'))
// Result: ['Content-Type', 'application/json']
Always convert both sides of the comparison — converting only one side is a common source of bugs. For related comparison techniques, see how to check if a string contains a substring in JavaScript.
2. Locale-Specific Conversion with toLocaleUpperCase()
The standard toUpperCase() uses Unicode default case mappings, which can produce incorrect results for certain languages. Use toLocaleUpperCase() when handling locale-sensitive text.
// Turkish has special casing rules for dotless i
const turkishText = 'istanbul'
// Default toUpperCase — incorrect for Turkish
console.log(turkishText.toUpperCase())
// Result: 'ISTANBUL' (with dotted I — incorrect in Turkish)
// Locale-aware conversion — correct for Turkish
console.log(turkishText.toLocaleUpperCase('tr'))
// Result: 'İSTANBUL' (with dotted İ — correct)
// German lowercase ß converts to SS in uppercase
const germanText = 'straße'
console.log(germanText.toUpperCase())
// Result: 'STRASSE'
console.log(germanText.toLocaleUpperCase('de'))
// Result: 'STRASSE'
// Safe multilingual helper
const toUpper = (text, locale) => {
if (!text) return ''
return locale
? text.toLocaleUpperCase(locale)
: text.toUpperCase()
}
console.log(toUpper('café', 'fr')) // 'CAFÉ'
console.log(toUpper('hello')) // 'HELLO'
console.log(toUpper(null)) // ''
The Turkish İ/I distinction is the most commonly encountered locale issue. If your application serves Turkish users, always use toLocaleUpperCase('tr') to avoid incorrect casing.
3. Safe Uppercase with Nullish Values
Data from APIs or user input may be null or undefined. Calling toUpperCase() on these values throws a TypeError, so you need to guard against them.
// This throws: Cannot read properties of null
// null.toUpperCase()
// Optional chaining — returns undefined instead of throwing
const apiValue = null
console.log(apiValue?.toUpperCase())
// Result: undefined
// Nullish coalescing for a default value
const label = apiValue?.toUpperCase() ?? 'N/A'
// Result: 'N/A'
// Practical safe conversion function
const safeUpperCase = (value) => {
if (value == null) return ''
return String(value).toUpperCase()
}
console.log(safeUpperCase('hello')) // 'HELLO'
console.log(safeUpperCase(null)) // ''
console.log(safeUpperCase(undefined)) // ''
console.log(safeUpperCase(42)) // '42'
// Processing API response data
const users = [
{ name: 'alice', role: 'admin' },
{ name: 'bob', role: null },
{ name: null, role: 'editor' }
]
const formatted = users.map(user => ({
name: user.name?.toUpperCase() ?? 'UNKNOWN',
role: user.role?.toUpperCase() ?? 'UNASSIGNED'
}))
// [
// { name: 'ALICE', role: 'ADMIN' },
// { name: 'BOB', role: 'UNASSIGNED' },
// { name: 'UNKNOWN', role: 'EDITOR' }
// ]
Optional chaining (?.) and nullish coalescing (??) are the modern JavaScript way to handle nullable values cleanly. Use String(value) when you need to handle non-string types gracefully.
4. Formatting Display Text
Uppercase is commonly used for headings, labels, badges, and status indicators. Rather than applying CSS text-transform, JavaScript conversion is needed when the uppercase text must be used in data processing, not just display.
// Status badge formatting
const formatStatus = (status) => {
const statusMap = {
active: { label: 'ACTIVE', color: 'success' },
pending: { label: 'PENDING', color: 'warning' },
inactive: { label: 'INACTIVE', color: 'danger' }
}
const key = status.toLowerCase()
return statusMap[key] ?? { label: status.toUpperCase(), color: 'secondary' }
}
console.log(formatStatus('active'))
// { label: 'ACTIVE', color: 'success' }
// Generate constant-style names from strings
const toConstantCase = (str) => {
return str
.replace(/([a-z])([A-Z])/g, '$1_$2')
.replace(/[\s-]+/g, '_')
.toUpperCase()
}
console.log(toConstantCase('backgroundColor'))
// Result: 'BACKGROUND_COLOR'
console.log(toConstantCase('max-retry-count'))
// Result: 'MAX_RETRY_COUNT'
console.log(toConstantCase('api base url'))
// Result: 'API_BASE_URL'
// Enum-like object from array
const statuses = ['pending', 'active', 'archived', 'deleted']
const STATUS = Object.fromEntries(
statuses.map(s => [s.toUpperCase(), s])
)
// { PENDING: 'pending', ACTIVE: 'active', ARCHIVED: 'archived', DELETED: 'deleted' }
The toConstantCase function is useful when generating environment variable names or enum-like constants from user-friendly strings. This pattern appears in CoreUI React badge components where status labels need consistent uppercase formatting.
5. Uppercase in String Pattern Matching
Combining uppercase conversion with string methods enables flexible pattern matching and text processing.
// Case-insensitive startsWith / endsWith
const startsWithIgnoreCase = (str, prefix) =>
str.toUpperCase().startsWith(prefix.toUpperCase())
const endsWithIgnoreCase = (str, suffix) =>
str.toUpperCase().endsWith(suffix.toUpperCase())
console.log(startsWithIgnoreCase('JavaScript', 'java'))
// Result: true
console.log(endsWithIgnoreCase('report.PDF', '.pdf'))
// Result: true
// File extension validation
const allowedExtensions = ['.JPG', '.PNG', '.GIF', '.WEBP']
const isImageFile = (filename) => {
const ext = filename.slice(filename.lastIndexOf('.')).toUpperCase()
return allowedExtensions.includes(ext)
}
console.log(isImageFile('photo.jpg')) // true
console.log(isImageFile('doc.PDF')) // false
console.log(isImageFile('image.Png')) // true
// Highlight matching text (preserving original case)
const highlight = (text, query) => {
if (!query) return text
const upperText = text.toUpperCase()
const upperQuery = query.toUpperCase()
const index = upperText.indexOf(upperQuery)
if (index === -1) return text
return (
text.slice(0, index) +
'<mark>' + text.slice(index, index + query.length) + '</mark>' +
text.slice(index + query.length)
)
}
console.log(highlight('JavaScript Guide', 'script'))
// Result: 'Java<mark>Script</mark> Guide'
The highlight function demonstrates a key pattern: convert to uppercase for matching, but return the original-cased text. For more on checking string patterns, see how to check if a string starts with a substring in JavaScript and how to check if a string ends with a substring in JavaScript.
6. Capitalizing First Letters
While toUpperCase() converts entire strings, combining it with string slicing lets you capitalize only specific characters — useful for titles and sentence formatting.
// Capitalize first letter only
const capitalize = (str) => {
if (!str) return ''
return str[0].toUpperCase() + str.slice(1)
}
console.log(capitalize('hello'))
// Result: 'Hello'
// Title case — capitalize first letter of each word
const toTitleCase = (str) => {
return str
.toLowerCase()
.split(' ')
.map(word => word[0]?.toUpperCase() + word.slice(1))
.join(' ')
}
console.log(toTitleCase('the quick brown fox'))
// Result: 'The Quick Brown Fox'
console.log(toTitleCase('HELLO WORLD'))
// Result: 'Hello World'
// Sentence case — capitalize after periods
const toSentenceCase = (str) => {
return str
.toLowerCase()
.replace(/(^\s*\w|[.!?]\s+\w)/g, match => match.toUpperCase())
}
console.log(toSentenceCase('hello world. how are you? fine thanks!'))
// Result: 'Hello world. How are you? Fine thanks!'
The toTitleCase function first converts to lowercase to handle ALL CAPS input correctly, then capitalizes each word. For more on capitalization, see how to capitalize the first letter of a string in JavaScript.
Best Practice Note:
This is the same approach we use in CoreUI React components for creating consistent header text, button labels, and implementing case-insensitive search functionality across our component library.
For locale-specific uppercase conversion, use toLocaleUpperCase() which respects language-specific rules like Turkish dotted İ and German ß to SS. Always convert both strings to the same case before comparison. When processing untrusted data, guard against null and undefined with optional chaining before calling toUpperCase(). For the inverse operation, see how to convert a string to lowercase in JavaScript.



