- Get first letter of each word in a string, in JavaScript
- Alternative 1:
- Alternative 2:
- Javascript string first characters
- # Get the first Character of a String in JavaScript
- # Get the first Character of a String using bracket notation
- # Get the first Character of a String using String.at()
- # Get the first Character of a String using String.slice()
- # Get the first Character of a String using String.substring()
- # Get the first Character of a String using Array.from()
- # Additional Resources
Get first letter of each word in a string, in JavaScript
I think what you’re looking for is the acronym of a supplied string.
var str = "Java Script Object Notation"; var matches = str.match(/\b(\w)/g); // ['J','S','O','N'] var acronym = matches.join(''); // JSON console.log(acronym)
Note: this will fail for hyphenated/apostrophe’d words Help-me I’m Dieing will be HmImD . If that’s not what you want, the split on space, grab first letter approach might be what you want.
Here’s a quick example of that:
let str = "Java Script Object Notation"; let acronym = str.split(/\s/).reduce((response,word)=> response+=word.slice(0,1),'') console.log(acronym);
@StephanHoyer Correct. I suppose umlauts, hyphens, apostrophes, etc. — characters which we consider part of a word and not a word boundary.
I think you can do this with
Explanation: Obtain all /g the alphanumeric characters \w that occur after a non-alphanumeric character (i.e: after a word boundary \b ), put them on an array with .match() and join everything in a single string .join(»)
Depending on what you want to do you can also consider simply selecting all the uppercase characters:
'JavaScript Object Notation'.match(/[A-Z]/g).join('')
@JesseB: I don’t know, the alternative solution with split is kinda verbose and has to worry about multiple space characters in sequence and other separators like dots or commas.
@missingno I prefer verbosity if it is easier to understand and maintain ;p Some people just don’t understand regexes, so even though it’s more terse, it can lead to confusion and misuse. I agree with you on the handling of other separators though.
Easiest way without regex
var abbr = "Java Script Object Notation".split(' ').map(function(item)).join('');
This is made very simple with ES6
string.split(' ').map(i => i.charAt(0)) //Inherit case of each letter string.split(' ').map(i => i.charAt(0)).toUpperCase() //Uppercase each letter string.split(' ').map(i => i.charAt(0)).toLowerCase() //lowercase each letter
This ONLY works with spaces or whatever is defined in the .split(‘ ‘) method
string.split(' ') .map(i => i.charAt(0)) .toString() .toUpperCase().split(',')
@JimmyKane string.split(‘ ‘).map((item) => item.charAt(0)).join(»).toUpperCase() is probably what you’re looking for.
To add to the great examples, you could do it like this in ES6
const x = "Java Script Object Notation".split(' ').map(x => x[0]).join(''); console.log(x); // JSON
and this works too but please ignore it, I went a bit nuts here 🙂
const [j,s,o,n] = "Java Script Object Notation".split(' ').map(x => x[0]); console.log(`$$$$`);
@BotNet flaw: i think i solved it after excruciating 3 days of regular expressions tutorials:
(used to catch m of I’m) because of the word boundary, it seems to work for me that way.
It’s important to trim the word before splitting it, otherwise, we’d lose some letters.
const getWordInitials = (word: string): string => < const bits = word.trim().split(' '); return bits .map((bit) =>bit.charAt(0)) .join('') .toUpperCase(); >;
$ getWordInitials(«Java Script Object Notation»)
var text = ''; var arr = "Java Script Object Notation".split(' '); for(i=0;i alert(text);
Using map (from functional programming)
'use strict'; function acronym(words) < if (!words) < return ''; >var first_letter = function(x) < if (x) < return x[0]; >else < return ''; >>; return words.split(' ').map(first_letter).join(''); >
Alternative 1:
you can also use this regex to return an array of the first letter of every word
// in case the input is lowercase & there's a word with apostrophe const toAbbr = (str) => < return str.match(/(?<=(\s|^))[a-z]/gi) .join('') .toUpperCase(); >; toAbbr("java script object notation"); //result JSON
(by the way, there are also negative lookbehind , positive lookahead , negative lookahead , if you want to learn more)
Alternative 2:
match all the words and use replace() method to replace them with the first letter of each word and ignore the space (the method will not mutate your original string)
// in case the input is lowercase & there's a word with apostrophe const toAbbr = (str) => < return str.replace(/(\S+)(\s*)/gi, (match, p1, p2) =>p1[0].toUpperCase()); >; toAbbr("java script object notation"); //result JSON // word = not space = \S+ = p1 (p1 is the first pattern) // space = \s* = p2 (p2 is the second pattern)
var str = "", abbr = ""; str = "Java Script Object Notation"; str = str.split(' '); for (i = 0; i < str.length; i++) < abbr += str[i].substr(0,1); >alert(abbr);
If you came here looking for how to do this that supports non-BMP characters that use surrogate pairs:
initials = str.split(' ') .map(s => String.fromCodePoint(s.codePointAt(0) || '').toUpperCase()) .join('');
Works in all modern browsers with no polyfills (not IE though)
Getting first letter of any Unicode word in JavaScript is now easy with the ECMAScript 2018 standard:
This regex finds any Unicode letter (see the last \p ) that is not preceded with any other letter that can optionally have diacritic symbols (see the (?
To emulate a fully Unicode-aware \b , you’d need to add a digit matching pattern and connector punctuation:
It works in Chrome, Firefox (since June 30, 2020), Node.js, and the majority of other environments (see the compatibility matrix here), for any natural language including Arabic.
const regex = /(? [ "Ż", "Ł" ] // Extracting and concatenating into string console.log(string.match(regex).join("")) // => ŻŁ // Removing console.log(string.replace(regex, "")) // => erard yżwiński // Enclosing (wrapping) with a tag console.log(string.replace(regex, "$&")) // => Żerard Łyżwiński console.log("_Łukasz 1Żukowski".match(/(? null
Javascript string first characters
Last updated: Jan 2, 2023
Reading time · 4 min
# Get the first Character of a String in JavaScript
To get the first character of a string, call the String.charAt() method with an index of 0 .
The method will return a new string that only contains the first character of the original string.
Copied!const str = 'bobbyhadz.com'; const firstChar = str.charAt(0); console.log(firstChar); // 👉️ b
The String.charAt method returns the character at the specified index.
If the index doesn’t exist in the string, the method returns an empty string.
Copied!console.log('abc'.charAt(0)); // 👉️ a console.log(''.charAt(0)); // 👉️ ""
JavaScript indexes are zero-based. The first character in the string has an index of 0 and the last character has an index of str.length — 1 .
If you call the String.charAt() method with an index that doesn’t exist, it returns an empty string.
Copied!const str = ''; const firstChar = str.charAt(0); console.log(firstChar); // 👉️ ""
# Get the first Character of a String using bracket notation
An alternative approach is to directly access the index.
Accessing the string at index 0 returns the first character of the string.
Copied!const str = 'bobbyhadz.com'; const firstChar = str[0]; console.log(firstChar); // 👉️ b console.log('abcd'[0]); // 👉️ a
If we access the string at the specific index, we can avoid calling the charAt() method.
However, if you try to access the string at an index that doesn’t exist, undefined is returned.
Copied!const str = ''; const first = str[0]; console.log(first); // 👉️ undefined
This is the reason I prefer using the String.charAt() method.
I’d rather get an empty string than an undefined value if I access a string at an index that doesn’t exist.
# Get the first Character of a String using String.at()
The String.at() method returns a new string containing the character at the specified index.
Copied!const str = 'bobbyhadz.com'; const firstChar = str.at(0); console.log(firstChar); // 👉️ b console.log('abcd'.at(0)); // 👉️ a console.log(''.at(0)); // 👉️ undefined
The String.at method takes an integer and returns a new string containing the character at the specified position.
The String.at method allows for positive and negative integers.
You can use negative integers to count back from the end of the string.
Copied!const str = 'bobbyhadz.com'; const firstChar = str.at(0); console.log(firstChar); // 👉️ b console.log(str.at(-1)); // 👉️ m console.log(str.at(-2)); // 👉️ o console.log(str.at(-3)); // 👉️ c
The String.at() method is quite convenient when you need to count backward.
The String.charAt() method and bracket notation approach don’t support negative indexing.
Copied!console.log(str.at(-1)); // 👉️ m console.log(str.charAt(-1)); // 👉️ "" console.log(str[-1]); // 👉️ undefined
You can also use the String.slice() method to get the first character of a string.
# Get the first Character of a String using String.slice()
Specify a start index of 0 and a stop index of 1 to get the first character of a string using the slice() method.
Copied!const str = 'bobbyhadz.com'; const firstChar = str.slice(0, 1); console.log(firstChar); // 👉️ b
The String.slice method extracts a section of a string and returns it, without modifying the original string.
The String.slice() method takes the following arguments:
Name | Description |
---|---|
start index | The index of the first character to include in the returned substring |
end index | The index of the first character to exclude from the returned substring |
When only a single argument is passed to the String.slice() method, the slice goes to the end of the string.
The stop index is exclusive (up to, but not including), so the second character is not contained in the result.
If you try to get the first character of an empty string using slice() , an empty string is returned.
Copied!console.dir(''.slice(0, 1)); // 👉️ ''
# Get the first Character of a String using String.substring()
You can also use the String.substring() method in a similar way.
Copied!const str = 'bobbyhadz.com'; const firstChar = str.substring(0, 1); console.log(firstChar); // 👉️ b
The String.substring() method returns a slice of the string from the start index to the excluding end index.
The method takes the following parameters:
Name | Description |
---|---|
start index | The index of the first character to include in the returned substring |
end index | The index of the first character to exclude from the returned substring |
If no end index is specified the slice goes to the end of the string.
If you try to get the first character of an empty string using substring() , an empty string is returned.
Copied!console.dir(''.substring(0, 1)); // 👉️ ''
The substring() and slice() method seem identical from the previous 2 code samples.
However, there are a couple of differences between the String.substring() and the String.slice() methods:
- The substring() method swaps its start and end index if the start index is greater than the end index. The slice() method returns an empty string in this case.
Copied!const str = 'bobby'; console.log(str.substring(3, 0)); // 👉️ bob console.log(str.slice(3, 0)); // 👉️ ''
- If either of both arguments passed to substring() are negative, they are treated as if they were 0 .
Copied!const str = 'bobby'; console.log(str.substring(-3)); // 👉️ bobby console.log(str.slice(-3)); // 👉️ bby
When given a negative index, the slice() method counts backward from the end of the string to find the indexes.
# Get the first Character of a String using Array.from()
When working with Unicode strings that might contain emojis or other special characters, you might have to convert the string to an array of characters using Array.from() .
Copied!const str = '🐴bobbyhadz.com'; const firstChar = Array.from(str)[0]; console.log(firstChar); // '🐴'
The Array.from() method converts the supplied iterable to an array.
Copied!const str = '🐴bobbyhadz.com'; // [ // '🐴', 'b', 'o', 'b', // 'b', 'y', 'h', 'a', // 'd', 'z', '.', 'c', // 'o', 'm' // ] console.log(Array.from(str));
The last step is to access the character at index 0 .
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.