简体   繁体   中英

How can I pick out the first letter of the first word and then the second word from a string?

I have a function that returns Firstname and Lastname in a string. There is a requirement that there must always be both a first and last name:

var a = ens.userProfile.dataMap[row.createdBy].name

Can someone give me some advice on what I can use to modify the output so that a name like this that's returned into a:

John Smith

is changed to:

J Smith
var name = 'John Smith';
var names = name.split(' '); // split around the space
var result = names[0].substr(0, 1) + ' ' + names[1];

.substr(0, 1) works like this : https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/substr

Concatenate the names back together.

For completeness, including micha149 answer:

var name = 'John Smith';
var names = name.split(' '); // split around the space
var result = names[0].charAt(0) + ' ' + names[1];

.charAt(0) works like a so: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charAt

Hmm. Just with simple splitting?!

const nameParts = name.split(" ");
const firstLetter = nameParts[0].charAt(0);
const secondWord = nameParts[1];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM