Lodash title case (uppercase first letter of every word) - javascript

I'm looking through the lodash docs and other Stack Overflow questions - while there are several native JavaScript ways of accomplishing this task, is there a way I can convert a string to title case using purely lodash functions (or at least existing prototypal functions) so that I don't have to use a regular expression or define a new function?
e.g.
This string ShouLD be ALL in title CASe
should become
This String Should Be All In Title Case

This can be done with a small modification of startCase:
_.startCase(_.toLower(str));
console.log(_.startCase(_.toLower("This string ShouLD be ALL in title CASe")));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.min.js"></script>

_.startCase(_.camelCase(str))
For non-user-generated text, this handles more cases than the accepted answer
> startCase(camelCase('myString'))
'My String'
> startCase(camelCase('my_string'))
'My String'
> startCase(camelCase('MY_STRING'))
'My String'
> startCase(camelCase('my string'))
'My String'
> startCase(camelCase('My string'))
'My String'

with lodash version 4.
_.upperFirst(_.toLower(str))

'This string ShouLD be ALL in title CASe'
.split(' ')
.map(_.capitalize)
.join(' ');

There are mixed answers to this question.
Some are recommending using _.upperFirst while some recommending _.startCase.
Know the difference between them.
i) _.upperFirst will transform the first letter of your string, then string might be of a single word or multiple words but the only first letter of your string is transformed to uppercase.
_.upperFirst('jon doe')
output:
Jon doe
check the documentation https://lodash.com/docs/4.17.10#upperFirst
ii) _.startCase will transform the first letter of every word inside your string.
_.startCase('jon doe')
output:
Jon Doe
https://lodash.com/docs/4.17.10#startCase

That's the cleanest & most flexible implementation imo from testing it on my own use cases.
import { capitalize, map } from "lodash";
const titleCase = (str) => map(str.split(" "), capitalize).join(" ");
// titleCase("ALFRED NÚÑEZ") => "Alfred Núñez"
// titleCase("alfred núñez") => "Alfred Núñez"
// titleCase("AlFReD nÚñEZ") => "Alfred Núñez"
// titleCase("-") => "-"

From https://github.com/lodash/lodash/issues/3383#issuecomment-430586750
'JHON&JOHN C/O DR. BLah'.replace(/\w+/g, _.capitalize);
result:
'Jhon&John C/O Dr. Blah'

Here's a way using ONLY lodash methods and no builtin methods:
_.reduce(_.map(_.split("Hello everyOne IN the WOrld", " "), _.capitalize), (a, b) => a + " " + b)

This can be done with only lodash
properCase = string =>
words(string)
.map(capitalize)
.join(' ');
const proper = properCase('make this sentence propercase');
console.log(proper);
//would return 'Make This Sentence Propercase'

var s = 'This string ShouLD be ALL in title CASe';
_.map(s.split(' '), (w) => _.capitalize(w.toLowerCase())).join(' ')
Unless i missed it, lodash doesnt have its own lower/upper case methods.

const titleCase = str =>
str
.split(' ')
.map(str => {
const word = str.toLowerCase()
return word.charAt(0).toUpperCase() + word.slice(1)
})
.join(' ')
You can also split out the map function to do separate words

Below code will work perfectly:
var str = "TITLECASE";
_.startCase(str.toLowerCase());

Not as concise as #4castle's answer, but descriptive and lodash-full, nonetheless...
var basicTitleCase = _
.chain('This string ShouLD be ALL in title CASe')
.toLower()
.words()
.map(_.capitalize)
.join(' ')
.value()
console.log('Result:', basicTitleCase)
console.log('Exact Match:' , basicTitleCase === 'This String Should Be All In Title Case')
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.min.js"></script>

Here's another solution for my use case:
"devil's backbone"
Simply:
function titleCase (str) {
return _.map(str.split(' '), _.upperFirst).join(' ');
}
Using startCase would remove the apostrophe, so I had to work around that limitation. The other solutions seemed pretty convoluted. I like this as it's clean, easy to understand.

with lodash 4, you can use _.capitalize()
_.capitalize('JOHN')
It returns 'John'
See https://lodash.com/docs/4.17.5#capitalize for details

you can simply use the lowdash capitalize methode , it Converts the first character of string to upper case and the remaining to lower case.
https://lodash.com/docs/#capitalize
const str = 'titlecase this string ';
_.capitalize(str); //Titlecase This String

Related

the usage of 'map' method modifying inside contents, javascript

https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/title-case-a-sentence
Hi,
I'm practicing a basic algorithm from Freecodecamp.com.
The instruction is below.
Return the provided string with the first letter of each word
capitalized. Make sure the rest of the word is in lower case.
For the purpose of this exercise, you should also capitalize
connecting words like "the" and "of".
And this is my code.
const titleCase = str => {
let result = str.split(' ');
result = result.map(t => {
t = t.toLowerCase();
t[0] = t[0].toUpperCase();
return t;
});
return result.join(' ');
};
console.log(titleCase("I'm a little tea pot"));
Result
i'm a little tea pot
This is what I thought.
Extract a whole string into pieces by whitespace.
Make it lowercase.
Make only first letter uppercase.
return the result.
However, a problem is line:5 doesn't affect the result. The first letter doesn't change.
Am I missing something, right? It seems I misunderstand some concepts about map method.
Could you give some advice to fix that?
Thanks in advance.
The reason your code doesn't work as you would think is documented in the MDN String documentation.
When using bracket notation for character access, attempting to delete or assign a value to these properties will not succeed. The properties involved are neither writable nor configurable.
The alternative approach is to concatentate the first character after being converted to uppercase with the remaining string (excluding first character).
const titleCase = str => {
return str.toLowerCase()
.split(' ')
.map(w => `${w[0].toUpperCase()}${w.substring(1)}`)
.join(' ');
};
console.log(titleCase("I'm a little tea pot"));
Looks like the assignment on strings doesn't work like that in Javascript, too bad, it's intuitively correct.
So, use a string splice, which doesn't exist, so split the string into an array of characters with str.split(''), and use array splice.
The splice modifies the input array in place, so you don't need to re-assign it.
const str = "hello";
var rayy = str.split(''); // ['h', 'e', 'l', 'l', 'o']
rayy.splice(0, 1, rayy[0].toUpperCase()); // returns ['h], but rayy is now modified in place to ['H', 'e', 'l', 'l', 'o']
const str2 = rayy.join(''); // "Hello"
Your usage of map is adept and apt.
very elegantly looks with methods chaining - split+map+join
and patterns of string `${var1}${var2}` - in left back quote " ` "
var1 - item[0].toUpperCase() - first symbol toUpperCase
var2 - item.substring(1) - killing first symbol
.toLowerCase() - other symbols toLowerCase
const titleCase = (str) => str.split(' ')
.map(item => (`${item[0].toUpperCase()}${item.substring(1).toLowerCase()}`))
.join(' ')
console.log(titleCase("I'm a litTLE tea pot"));

How to check if a string contains a WORD in javascript? [duplicate]

This question already has answers here:
How to check if a string contain specific words?
(11 answers)
Closed 3 years ago.
So, you can easily check if a string contains a particular substring using the .includes() method.
I'm interested in finding if a string contains a word.
For example, if I apply a search for "on" for the string, "phones are good", it should return false. And, it should return true for "keep it on the table".
You first need to convert it into array using split() and then use includes()
string.split(" ").includes("on")
Just need to pass whitespace " " to split() to get all words
This is called a regex - regular expression
You can use of 101regex website when you need to work around them (it helps). Words with custom separators aswell.
function checkWord(word, str) {
const allowedSeparator = '\\\s,;"\'|';
const regex = new RegExp(
`(^.*[${allowedSeparator}]${word}$)|(^${word}[${allowedSeparator}].*)|(^${word}$)|(^.*[${allowedSeparator}]${word}[${allowedSeparator}].*$)`,
// Case insensitive
'i',
);
return regex.test(str);
}
[
'phones are good',
'keep it on the table',
'on',
'keep iton the table',
'keep it on',
'on the table',
'the,table,is,on,the,desk',
'the,table,is,on|the,desk',
'the,table,is|the,desk',
].forEach((x) => {
console.log(`Check: ${x} : ${checkWord('on', x)}`);
});
Explaination :
I am creating here multiple capturing groups for each possibily :
(^.*\son$) on is the last word
(^on\s.*) on is the first word
(^on$) on is the only word
(^.*\son\s.*$) on is an in-between word
\s means a space or a new line
const regex = /(^.*\son$)|(^on\s.*)|(^on$)|(^.*\son\s.*$)/i;
console.log(regex.test('phones are good'));
console.log(regex.test('keep it on the table'));
console.log(regex.test('on'));
console.log(regex.test('keep iton the table'));
console.log(regex.test('keep it on'));
console.log(regex.test('on the table'));
You can .split() your string by spaces (\s+) into an array, and then use .includes() to check if the array of strings has your word within it:
const hasWord = (str, word) =>
str.split(/\s+/).includes(word);
console.log(hasWord("phones are good", "on"));
console.log(hasWord("keep it on the table", "on"));
If you are worried about punctuation, you can remove it first using .replace() (as shown in this answer) and then split():
const hasWord = (str, word) =>
str.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g,"").split(/\s+/).includes(word);
console.log(hasWord("phones are good son!", "on"));
console.log(hasWord("keep it on, the table", "on"));
You can split and then try to find:
const str = 'keep it on the table';
const res = str.split(/[\s,\?\,\.!]+/).some(f=> f === 'on');
console.log(res);
In addition, some method is very efficient as it will return true if any predicate is true.
You can use .includes() and check for the word. To make sure it is a word and not part of another word, verify that the place you found it in is followed by a space, comma, period, etc and also has one of those before it.
A simple version could just be splitting on the whitespace and looking through the resulting array for the word:
"phones are good".split(" ").find(word => word === "on") // undefined
"keep it on the table".split(" ").find(word => word === "on") // "on"
This just splits by whitespace though, when you need parse text (depending on your input) you'll encounter more word delimiters than whitespace. In that case you could use a regex to account for these characters.
Something like:
"Phones are good, aren't they? They are. Yes!".split(/[\s,\?\,\.!]+/)
I would go with the following assumptions:
Words the start of a sentence always have a trailing space.
Words at the end of a sentence always have a preceding space.
Words in the middle of a sentence always have a trailing and preceding space.
Therefore, I would write my code as follows:
function containsWord(word, sentence) {
return (
sentence.startsWith(word.trim() + " ") ||
sentence.endsWith(" " + word.trim()) ||
sentence.includes(" " + word.trim() + " "));
}
console.log(containsWord("test", "This is a test of the containsWord function."));
Try the following -
var mainString = 'codehandbook'
var substr = /hand/
var found = substr.test(mainString)
if(found){
console.log('Substring found !!')
} else {
console.log('Substring not found !!')
}

Convert different strings to snake_case in Javascript

I know that we have a question similar to this but not quite the same.
I'm trying to make my function work which takes in a string as an argument and converts it to snake_case . It works most of the time with all the fancy !?<>= characters but there is one case that it can't convert and its camelCase .
It fails when I'm passing strings like snakeCase. It returns snakecase instead of snake_case.
I tried to implement it but I ended up just messing it up even more..
Can I have some help please?
my code:
const snakeCase = string => {
string = string.replace(/\W+/g, " ").toLowerCase().split(' ').join('_');
if (string.charAt(string.length - 1) === '_') {
return string.substring(0, string.length - 1);
}
return string;
}
You need to be able to detect the points at which an upper-case letter is in the string following another letter (that is, not following a space). You can do this with a regular expression, before you call toLowerCase on the input string:
\B(?=[A-Z])
In other words, a non-word boundary, followed by an upper case character. Split on either the above, or on a literal space, then .map the resulting array to lower case, and then you can join by underscores:
const snakeCase = string => {
return string.replace(/\W+/g, " ")
.split(/ |\B(?=[A-Z])/)
.map(word => word.toLowerCase())
.join('_');
};
console.log(snakeCase('snakeCase'));
Let's try that again Stan... this should do snake_case while realising that CamelCASECapitals = camel_case_capitals. It's basically the accepted answer with a pre-filter.
let splitCaps = string => string
.replace(/([a-z])([A-Z]+)/g, (m, s1, s2) => s1 + ' ' + s2)
.replace(/([A-Z])([A-Z]+)([^a-zA-Z0-9]*)$/, (m, s1, s2, s3) => s1 + s2.toLowerCase() + s3)
.replace(/([A-Z]+)([A-Z][a-z])/g,
(m, s1, s2) => s1.toLowerCase() + ' ' + s2);
let snakeCase = string =>
splitCaps(string)
.replace(/\W+/g, " ")
.split(/ |\B(?=[A-Z])/)
.map(word => word.toLowerCase())
.join('_');
> a = ['CamelCASERules', 'IndexID', 'CamelCASE', 'aID',
'theIDForUSGovAndDOD', 'TheID_', '_IDOne']
> _.map(a, snakeCase)
['camel_case_rules', 'index_id', 'camel_case', 'a_id', 'the_id_for_us_gov_and_dod',
'the_id_', '_id_one']
// And for the curious, here's the output from the pre-filter:
> _.map(a, splitCaps)
['Camel case Rules', 'Index Id', 'Camel Case', 'a Id', 'the id For us Gov And Dod',
'The Id_', '_id One']
Suppose the string is Hello World? and you want the returned value as hello_world? (with the character, then follow the below code)
const snakeCase = (string) => {
return string.replace(/\d+/g, ' ')
.split(/ |\B(?=[A-Z])/)
.map((word) => word.toLowerCase())
.join('_');
};
Example
snakeCase('Hello World?')
// "hello_world?"
snakeCase('Hello & World')
// "hello_&_world"
EDIT: It turns out this answer isn’t fool proof. The fool, being me ;-) Please check out a better one by Orwellophile here: https://stackoverflow.com/a/69878219/5377276
——
I think this one should cover all the bases 😄
It was inspired by #h0r53's answer to the accepted answer. However it evolved into a more complete function, as it will convert any string, camelCase, kebab-case or otherwise into snake_case the way you'd expect it, containing only a-z and 0-9 characters, usable for function and variable names:
convert_to_snake_case(string) {
return string.charAt(0).toLowerCase() + string.slice(1) // lowercase the first character
.replace(/\W+/g, " ") // Remove all excess white space and replace & , . etc.
.replace(/([a-z])([A-Z])([a-z])/g, "$1 $2$3") // Put a space at the position of a camelCase -> camel Case
.split(/\B(?=[A-Z]{2,})/) // Now split the multi-uppercases customerID -> customer,ID
.join(' ') // And join back with spaces.
.split(' ') // Split all the spaces again, this time we're fully converted
.join('_') // And finally snake_case things up
.toLowerCase() // With a nice lower case
}
Conversion examples:
'snakeCase' => 'snake_case'
'CustomerID' => 'customer_id'
'GPS' => 'gps'
'IP-address' => 'ip_address'
'Another & Another, one too' => 'another_another_one_too'
'random ----- Thing123' => 'random_thing123'
'kebab-case-example' => 'kebab_case_example'
There is method in lodash named snakeCase(). You can consider that as well.
https://lodash.com/docs/4.17.15#snakeCase
Orwellophile's answer does not work for uppercase words delimited by a space:
E.g: 'TEST CASE' => t_e_s_t_case
The following solution does not break consecutive upper case characters and is a little shorter:
const snakeCase = str =>
str &&
str
.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
.map(x => x.toLowerCase())
.join('_');
However, trailing underscores after uppercase words (examples from Orwellophile as well), do not work properly.
E.g: 'TheID_' => the_i_d
Taken from https://www.w3resource.com/javascript-exercises/fundamental/javascript-fundamental-exercise-120.php.

Javascript: Manipulate string to remove underscore and capitalize letter after

Lets say I am receiving a string like so:
var string = "example_string"
var otherString = "example_string_two"
And I want to manipulate it to output like this:
string = "exampleString"
otherString = "ExampleStringTwo"
Basically, I want to find any underscore characters in a string and remove them. If there is a letter after the underscore, then it should be capitalized.
Is there a fast way to do this in regex?
You could look for the start of the string or underscore and replace the found part with an uppercase character.
var string= 'example_string_two';
console.log(string.replace(/(^|_)./g, s => s.slice(-1).toUpperCase()));
A regular expression like /_([a-zA-Z])/g will do with a proper callback function in String.prototype.replace. See snippet below.
function camelize (dasherizedStr) {
return dasherizedStr
.replace(/_([a-zA-Z])/g, function (m1, m2) {
return m2.toUpperCase()
});
}
console.log('example_string_foo:', camelize('example_string_foo'));
console.log('foo_Bar:', camelize('foo_Bar'));
Yeah you could use regex methods and simply replace the underscore and i'll give you an example :
var string = "example_string"
string.replace('_','');
But you could also do this in classic JS, which is pretty fast in on it's self
Example:
var string = "example_string"
string.split('_').join('');
If you are looking for something more, please comment below.
You can easily replace using JavaScript
var string= 'example_string_two';
console.log(string.replaceAll('_', ' '))
Output : 'example string two'
you can replace any word, underscore, dashes using javascript
here is code
var str= 'example_string_two';
console.log(var newStr = str.replace("_", " "));
output:
examplestringtwo

Get first letter of each word in a string, in JavaScript

How would you go around to collect the first letter of each word in a string, as in to receive an abbreviation?
Input: "Java Script Object Notation"
Output: "JSON"
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);
I think you can do this with
'Aa Bb'.match(/\b\w/g).join('')
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('')
Easiest way without regex
var abbr = "Java Script Object Notation".split(' ').map(function(item){return item[0]}).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
ie, .split(', ') .split('; '), etc.
string.split(' ') .map(i => i.charAt(0)) .toString() .toUpperCase().split(',')
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(`${j}${s}${o}${n}`);
#BotNet flaw:
i think i solved it after excruciating 3 days of regular expressions tutorials:
==> I'm a an animal
(used to catch m of I'm) because of the word boundary, it seems to work for me that way.
/(\s|^)([a-z])/gi
Try -
var text = '';
var arr = "Java Script Object Notation".split(' ');
for(i=0;i<arr.length;i++) {
text += arr[i].substr(0,1)
}
alert(text);
Demo - http://jsfiddle.net/r2maQ/
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
/(?<=(\s|^))[a-z]/gi
(?<=(\s|^)) is called positive lookbehind which make sure the element in our search pattern is preceded by (\s|^).
so, for your case:
// 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)
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")
$ "JSON"
How about this:
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);
Working Example.
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:
/(?<!\p{L}\p{M}*)\p{L}/gu
This regex finds any Unicode letter (see the last \p{L}) that is not preceded with any other letter that can optionally have diacritic symbols (see the (?<!\p{L}\p{M}*) negative lookbehind where \p{M}* matches 0 or more diacritic chars). Note that u flag is compulsory here for the Unicode property classes (like \p{L}) to work correctly.
To emulate a fully Unicode-aware \b, you'd need to add a digit matching pattern and connector punctuation:
/(?<!\p{L}\p{M}*|[\p{N}\p{Pc}])\p{L}/gu
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.
Quick test:
const regex = /(?<!\p{L}\p{M}*)\p{L}/gu;
const string = "Żerard Łyżwiński";
// Extracting
console.log(string.match(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, "<span>$&</span>")) // => <span>Ż</span>erard <span>Ł</span>yżwiński
console.log("_Łukasz 1Żukowski".match(/(?<!\p{L}\p{M}*|[\p{N}\p{Pc}])\p{L}/gu)); // => null
In ES6:
function getFirstCharacters(str) {
let result = [];
str.split(' ').map(word => word.charAt(0) != '' ? result.push(word.charAt(0)) : '');
return result;
}
const str1 = "Hello4 World65 123 !!";
const str2 = "123and 456 and 78-1";
const str3 = " Hello World !!";
console.log(getFirstCharacters(str1));
console.log(getFirstCharacters(str2));
console.log(getFirstCharacters(str3));
Output:
[ 'H', 'W', '1', '!' ]
[ '1', '4', 'a', '7' ]
[ 'H', 'W', '!' ]
This should do it.
var s = "Java Script Object Notation",
a = s.split(' '),
l = a.length,
i = 0,
n = "";
for (; i < l; ++i)
{
n += a[i].charAt(0);
}
console.log(n);
The regular expression versions for JavaScript is not compatible with Unicode on older than ECMAScript 6, so for those who want to support characters such as "å" will need to rely on non-regex versions of scripts.
Event when on version 6, you need to indicate Unicode with \u.
More details: https://mathiasbynens.be/notes/es6-unicode-regex
Yet another option using reduce function:
var value = "Java Script Object Notation";
var result = value.split(' ').reduce(function(previous, current){
return {v : previous.v + current[0]};
},{v:""});
$("#output").text(result.v);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="output"/>
This is similar to others, but (IMHO) a tad easier to read:
const getAcronym = title =>
title.split(' ')
.map(word => word[0])
.join('');
ES6 reduce way:
const initials = inputStr.split(' ').reduce((result, currentWord) =>
result + currentWord.charAt(0).toUpperCase(), '');
alert(initials);
Try This Function
const createUserName = function (name) {
const username = name
.toLowerCase()
.split(' ')
.map((elem) => elem[0])
.join('');
return username;
};
console.log(createUserName('Anisul Haque Bhuiyan'));

Categories

Resources