admin管理员组文章数量:1430061
In Javascript, I want to show in a history of events the first initial of the first name and the full last name.
Example:
let name = "Mike Jones"
Desired result ---> "M. Jones"
In Javascript, I want to show in a history of events the first initial of the first name and the full last name.
Example:
let name = "Mike Jones"
Desired result ---> "M. Jones"
Share Improve this question asked Sep 15, 2021 at 14:46 Blackwell805Blackwell805 511 silver badge8 bronze badges 4-
2
Have a look at
string.split()
andstring.substr()
. – gen_Eric Commented Sep 15, 2021 at 14:49 - 1 please make an attempt before asking – depperm Commented Sep 15, 2021 at 14:50
- This question does not contain enough research and is very vague. If you would at least try to research a little bit on what you are trying to do, I am certain that you will see some results. – Joe Commented Sep 15, 2021 at 14:50
- Thank you for the feedback! – Blackwell805 Commented Sep 15, 2021 at 20:48
2 Answers
Reset to default 5You should utilize string.split()
to split up the parts of the name, then use string.substr()
to get the first initial, then use array.join()
to glue the parts back together.
let name = "Mike Jones" // Who? Mike Jones
// Create an array containing each of the words in the name
var names = name.split(/\s+/);
// Replaces the first name with an initial, followed by a period.
names[0] = names[0].substr(0, 1) + ".";
// Glue the pieces back together.
var name_abbr = names.join(' ');
console.log(name_abbr);
Or if you want to get fancy, you could use some regex to get the first letter of the first word, and then everything else, and then just put a period between them.
let name = "Mike Jones" // Who? Mike Jones
var parts = name.match(/^([a-zA-Z])[^\s]*(.*)$/);
var abbr_name = parts[1] + "." + parts[2];
console.log(abbr_name);
If you wanted to support multiple initials you could do something like:
let name = "Mike Fred Jones"
//string.split() name by [space].
var names = name.split(" ")
//Temporary variable for initialled name.
var newname = ""
//For each name in the names array.
for (n in names){
//make sure its not the last.
if (String(names[n]).valueOf() != String(names[names.length-1]).valueOf()){
//Append the first letter of the name and [.]
newname = newname + names[n][0] + "."
}
}
//Append initials, [space], and last name.
newname = newname + " " + names[names.length-1]
console.log(newname) //Outputs M.F. Jones
本文标签: javascriptDisplay First Initial of First name and full Last nameStack Overflow
版权声明:本文标题:javascript - Display First Initial of First name and full Last name - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745548510a2662819.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论